Ruby ShortcutsOptional Node
Ruby has many shortcuts for writing concise code and assigning variables. They're not essential, so feel free to skip this page.
Ruby lets you assign multiple variables on one line:
a, b, c = 1, 2, 3 puts a, b, c
1 2 3
Here's the long way to increment a variable:
a = a + 1
You can replace it with:
a += 1
This also works for other operators:
j = 3 #=> 3 j *= 4 #=> 12 j -= 2 #=> 10 j /= 2 #=> 5
j started at 3 and ended up at 5 after the above operations.
Here's the long way to assign a variable when you have a true/false condition:
if condition1 num = 10 else num = 20 end
num will be set to 10, otherwise
num will be set to 20.
The above code can be shortened into one line with a ternary operator:
num = condition1 ? 10 : 20
This assigns the initial variable (
num) to to the first value (
10) if the condition (
condition1) is true, and otherwise it assigns the variable to the second value (
We want to set
name isn't nil, but otherwise we want to set
person_name to "Anonymous".
Here's the long way to do it:
if name person_name = name else # name is nil or false person_name = "Anonymous" end
You could use a ternary operator here, but Ruby lets you do this even more concisely:
name = person_name || "Anonymous"
Or Statements return the first true/non-nil value they encounter, so here
name will be set to
person_name if it's not nil, but otherwise
name will be set to "Anonymous".
Ruby even as a shorthand to assign a value if the value itself isn't nil:
name ||= "Anonymous"
This will only set
name to "Anonymous" if
name is nil (or false).