Ruby 中的并行赋值
在Ruby中,多个赋值可以在一个操作中完成。多个赋值包含具有多个lvalue 、多个rvalue或两者的表达式。 =运算符右侧赋值的顺序必须与左侧变量的顺序相同。分配有效地并行执行,因此分配的值不受分配本身的影响。
句法:
lvalue1,... = rvalue2, ...
参数:左侧变量称为左值,右侧变量称为右值。
- 如果一个赋值有一个左值和多个右值,那么 Ruby 会创建一个数组来保存右值并将该数组分配给左值。
- 如果赋值的左值多于右值,则多余的左值将设置为 nil。
- 如果一个赋值有多个左值和一个数组右值,则每个数组值从左到右分配给一个左值。
- 如果最后一个左值前面有一个星号( *也称为splat运算符),则所有剩余的右值将被收集并作为数组分配给该左值。
- 类似地,如果最后一个右值是一个数组,您可以在它前面加上一个星号,这可以有效地将它扩展为它的组成值。 (如果右值是右侧唯一的东西,则不需要这样做,数组将自动扩展。)
示例 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
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
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
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
输出:
Result 1:
2
3
4
Result 2:
9
3
5
示例 2:
红宝石
# 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
输出:
One lvalue and multiple rvalue:
2
3
4
Three lvalues and two rvalues:
2
3
NilClass
示例 3:
红宝石
# 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
输出:
Result 1:
2
3
4
Result 2:
1
示例 4:
红宝石
# 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
输出:
2
4
6