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.
Syntax:
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.)
Example 1:
Ruby
a, b, c = 2 , 3 , 4
puts "Result 1:"
puts a, b, c
a, b, c = [ 9 , 3 , 5 ]
puts "Result 2:"
puts a, b, c
|
Output:
Result 1:
2
3
4
Result 2:
9
3
5
Example 2:
Ruby
val = 2 , 3 , 4
puts "One lvalue and multiple rvalue:"
puts val
val1, val2, val3 = 2 , 3
puts "Three lvalues and two rvalues:"
puts val1, val2, val3. class
|
Output:
One lvalue and multiple rvalue:
2
3
4
Three lvalues and two rvalues:
2
3
NilClass
Example 3:
Ruby
num1, *num2 = 1 , 2 , 3 , 4
puts "Result 1:"
puts num2
num3 = [ 1 , 2 , 3 , 4 ]
num1, num2 = 15 , *num3
puts "Result 2:"
puts num2
|
Output:
Result 1:
2
3
4
Result 2:
1
Example 4:
Ruby
def modify(x, y, z)
x = x + 1
y = y + 2
z = z + 3
return x, y, z
end
a, b, c = modify( 1 , 2 , 3 )
puts a, b, c
|
Output:
2
4
6
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
27 Jul, 2020
Like Article
Save Article