Ruby Shortcuts

Optional Node
Collapse Content

Ruby has many shortcuts for writing concise code and assigning variables. They're not essential, so feel free to skip this page.

Multiple Variables

Ruby lets you assign multiple variables on one line:

a, b, c = 1, 2, 3
puts a, b, c 

This outputs:

1
2
3

Incrementing Variables

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.

Ternary Operator

Here's the long way to assign a variable when you have a true/false condition:

if condition1
  num = 10
else
  num = 20
end

if condition1 is true, 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 (20).

Nil Assignment

We want to set person_name to name if 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).

Challenge

What will the following code output?

currency_input = nil
amount = 5
amount += 3
currency = currency_input || "Dollars"
puts "#{amount} #{currency}"

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us