Ruby Parallel Assignment

Parallel Assignment

Ruby supports the parallel assignment of variables which can be done in a single operation. Therefore you can declare several variables to the left as an assignment operator and several values to the right. The order of the values to the right must be same to the variables on the left. See the following syntax :

l1, l2, l3 = "Python", "Ruby", "PHP"

The assignment also swap the values of variables :

irb(main):038:0> n1 = 100
=> 100
irb(main):039:0> n2 = 200
=> 200
irb(main):040:0> n1, n2 = n2, n1
=> [200, 100]

It is also possible to make multiple assignments from the values returned by a method. Here is an example :

def add_values( x, y, z ) 
x = x/2
y = y/3
z = z/4
return x, y, z 

puts(add_values(10, 20 , 30))



Previous: Ruby Assignment Operators
Next: Ruby Bitwise Operators

Follow us on Facebook and Twitter for latest update.