Open In App

Parallel Assignment in Ruby

Last Updated : 27 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Ruby program to demonstrate parallel assignment
  
# Same number of lvalues and rvalues
a, b, c = 2, 3, 4
puts "Result 1:"
puts a, b, c
  
# Same as a, b, c = 2, 3, 4
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




# Ruby program to demonstrate parallel assignment
  
# One lvalue and multiple rvalues
# rvalues as an array is assigned to lvalue
val = 2, 3, 4
puts "One lvalue and multiple rvalue:"
puts val
  
# Three lvalues and two rvalues
# val3 is set to nil
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




# Ruby program to demonstrate splat 
# operator with parallel assignment
  
# same as num1, num2 = 1, [2, 3, 4]
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




# Ruby program to demonstrate parallel assignment
  
# Return multiple values 
# and assign them in parallel
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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads