5v3n.com

Multiple Assignment


rubyquicktips:

You can assign multiple values to multiple variables like this:

foo, bar = [1, 2]  # foo = 1; bar = 2
foo, bar = 1, 2    # foo = 1; bar = 2
foo, bar = 1       # foo = 1; bar = nil

F.e. this can be useful for splitting names:

>> name = "Joe Bloggs"
=> "Joe Bloggs"
>> firstname, lastname = name.split
=> ["Joe", "Bloggs"]
>> firstname
=> "Joe"
>> lastname
=> "Bloggs"
>> name
=> "Joe Bloggs"

Read more on assignment in Ruby.

What’s even more astonishing to me is the fact that you can easily swap two variables’ values without explicitly using a temporary value:

x, y = y, x

Can’t believe it? I had to test it myself, too:

irb(main):001:0> x = 5
=> 5
irb(main):002:0> y = 10
=> 10
irb(main):003:0> x , y = y , x
=> [10, 5]
irb(main):004:0> x
=> 10
irb(main):005:0> y
=> 5