In Ruby, you can do parallel assignment.
This means you can have several variables to the left or an assignment operator and several values to the right.
The values to the right will be assigned, in order, to the variables on the left, like this:
s1, s2, s3 = "A", "B", "C"
You can swap the values of variables by changing their orders on either side of the assignment operator:
i1 = 1 i2 = 2 i1, i2 = i2, i1 #=> i1 is now 2, i2 is 1 puts i1, i2
And you can make multiple assignments from the values returned by a method:
def returnArray( a, b, c ) a = "Hello, " + a b = "Hi, " + b c = "Good day, " + c return a, b, c end# w w w . ja va2 s .c o m x, y, z = returnArray( "A", "B", "C" ) puts x, y, z
If you specify more variables to the left than there are values on the right of an assignment, any "trailing" variables will be assigned nil:
def returnArray( a, b, c ) a = "Hello, " + a b = "Hi, " + b c = "Good day, " + c return a, b, c end# w ww. j a v a 2 s . c om x, y, z, extravar = returnArray( "A", "B", "C" ) # extravar = nil puts x, y, z, extravar
Multiple values returned by a method are put into an array.
When you put an array to the right of a multiple-variable assignment, its individual elements will be assigned to each variable, and once again if too many variables are supplied, the extra ones will be assigned nil:
s1, s2, s3 = ["Ding", "Dong", "Bell"] puts s1, s2, s3