Ruby parameter expansion

If you’re familiar with ruby, you probably have seen multiple assignment before which looks like

first, second = 1,2

or

first, second = [1,2]

but did you know you could do multiple assignment in method params like so:

def test
  yield [1,2]
end

test do |(first, second)|
  "First is #{first} and second is #{second}"
end

Say for example you have an method that returns an array of tuples (something that’s unfortunately pretty common) such as

[[user, users_dog], [user, users_dog],...]

Without knowing this trick, you might be tempted to do something like

tuples.reduce([]) do |results, ary|
  operate_on_user(ary[0]) # or .first
  operate_on_dog(ary[1]) # or .last
end

Which is hard to tell at first glance what ary[0] or ary[1] holds.

Using this trick you can clean this up like so

tuples.reduce([]) do |results, (user, dog)|
  operate_on_user(user)
  operate_on_dog(dog)
end

Boom! instantly more readable