## Ruby中的并行赋值算子是什么？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (26)

```def fib_up_to(max)
i1, i2 = 1, 1 # parallel assignment (i1 = 1 and i2 = 1)
while i1 <= max
yield i1
i1, i2 = i2, i1+i2
end
end
fib_up_to(100) {|f| print f, " " }```

```i1 = i2
i2 = i1+i2```

### 2 个回答

``````irb(main):020:0> a = 1, 2 # assign to a single variable
=> [1, 2]
irb(main):021:0> a
=> [1, 2]
irb(main):022:0> a, b = 1, 2 # unpack into separate variables
=> [1, 2]
irb(main):023:0> a
=> 1
irb(main):024:0> b
=> 2
irb(main):025:0> a, b = [1, 2, 3] # 3 is 'lost' as no receiving variable
=> [1, 2, 3]
irb(main):026:0> a
=> 1
irb(main):027:0> b
=> 2
irb(main):028:0> first, *rest = [1, 2, 3] # *rest consumes the remaining elements
=> [1, 2, 3]
irb(main):029:0> first
=> 1
irb(main):030:0> rest
=> [2, 3]
``````

``````def sum_and_difference(a, b)
a + b, a - b
end

sum, difference = sum_and_difference 5, 3
``````

``````def fib_up_to(max)
i1 = i2 = 1
while i1 <= max
yield i1
i1, i2 = i2, i1+i2
end
end

fib_up_to(100) {|f| print f, " " }
``````

`i1, i2 = 1, 1`在我看来，使用没有任何意义。但是这种分配对于第5行是有意义的。