Ruby: Multiple assignment
A handy feature of Ruby is that it lets you assign multiple variables at once. While doing this all the time is not encouraged, where it makes the code more readable/understandable it is certainly something to try.
It's as simple as:
first, second = 1, 2
puts first # 1
puts second # 2
third, fourth, last = [3, 4, 5]
puts third # 3
puts fourth # 4
puts last # 5
But beware, although the outcome technically makes sense this might be unexpected in some situations:
first, second = 1 # first is 1, second is nil
There are a heap of uses for this kind of thing.
# Reversing two variables
x = 1
y = 2
x, y = y, x # x is now 2, y is now 1
# Breaking up a name
name = "Nathan Hoad"
first_name, last_name = name.split
puts first_name # Nathan
puts last_name # Hoad
Personally, I think splitting names is one of the better examples of a good time to use multiple variable setting. What do you think?
If you liked this article then check out my free office sport app, Athletable.