amingilani amingilani - 1 month ago 14
Ruby Question

Why can I assign two variables corresponding to an array in Ruby?

After about a year of Ruby, I just saw this somewhere and my mind is blown. Why in the world does this work?

>> words = ['uno', 'dos']
=> ["uno", "dos"]
>> first, second = words
=> ["uno", "dos"]
>> first
=> "uno"
>> second
=> "dos"


Specifically, how does this work:

>> first, second = ['uno', 'dos']


Why can I do this? It makes no syntactical sense!

Answer

It makes no syntactical sense

But this is part of Ruby's syntax! In the Ruby docs it is known as array decomposition:

Like Array decomposition in method arguments you can decompose an Array during assignment using parenthesis:

(a, b) = [1, 2]

p a: a, b: b # prints {:a=>1, :b=>2}

You can decompose an Array as part of a larger multiple assignment:

a, (b, c) = 1, [2, 3]

p a: a, b: b, c: c # prints {:a=>1, :b=>2, :c=>3}

Since each decomposition is considered its own multiple assignment you can use * to gather arguments in the decomposition:

a, (b, *c), *d = 1, [2, 3, 4], 5, 6

p a: a, b: b, c: c, d: d
# prints {:a=>1, :b=>2, :c=>[3, 4], :d=>[5, 6]}

Edit

stackoverflow documentation for decomposition