Parallel Assignment in Ruby
In Ruby, multiple assignments can be done in a single operation. Multiple assignments contain an expression that has more than one lvalue, more than one rvalue, or both. The order of the values assigned to the right side of = operator must be the same as the variables on the left side. The assignments are effectively performed in parallel, so the values assigned are not affected by the assignment itself.
lvalue1,... = rvalue2, ...
Parameters: left side variables are called lvalues and right side variables are called rvalues.
- If an assignment has one lvalue and more than one rvalue, then Ruby creates an array to hold the rvalues and assigns that array to the lvalue.
- If an assignment has more lvalues than rvalues, then the excess lvalues are set to nil.
- If an assignment has more lvalues and a single array rvalue, then each array value is assigned to a single lvalue from left to right.
- If the last lvalue is preceded by an asterisk(* also called splat operator), all the remaining rvalues will be collected and assigned to that lvalue as an array.
- Similarly, if the last rvalue is an array, you can prefix it with an asterisk, which effectively expands it into its constituent values in place. (This is not necessary if the rvalue is the only thing on the right-hand side, the array will be expanded automatically.)
Result 1: 2 3 4 Result 2: 9 3 5
One lvalue and multiple rvalue: 2 3 4 Three lvalues and two rvalues: 2 3 NilClass
Result 1: 2 3 4 Result 2: 1
2 4 6