Parallel Assignment

I mentioned earlier that it is possible for a method to return multiple values, separated by commas. Often you will want to assign these returned values to a set of matching variables.

In Ruby, you can do this in a single operation by 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:

parallel_assign.rb

s1, s2, s3 = "Hickory", "Dickory", "Dock"

This ability not only gives you a shortcut way to make multiple assignments; it also lets you swap the values of variables (you just change their orders on either side of the assignment operator):

i1 = 1
i2 = 2

i1, i2 = i2, i1        #=> i1 is now 2, i2 is 1

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
x, y, z = returnArray( "Fred", "Bert", "Mary" )

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:

x, y, z, extravar = returnArray( "Fred", "Bert", "Mary" ) # extravar = nil

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"]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.245.1