Ruby 中的并行赋值运算符 [英] Parallel Assignment operator in Ruby

查看:37
本文介绍了Ruby 中的并行赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读《Programming in Ruby》一书中的一个示例:

I was going through an example from the Programming in Ruby book:

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, " " }

这只是打印最多 100 的斐波那契数列.没关系.当我用以下内容替换并行分配时:

This simply prints the Fibonacci numbers up to 100. That's fine. When I replace the parallel assignment with:

i1 = i2
i2 = i1+i2

我没有得到想要的输出.

I am not getting the desired output.

是否建议使用并行分配?我来自 Java 背景,看到这种类型的作业感觉很奇怪.

Is it advisable to use parallel assignments? I come from a Java background and it feels really weird to see this type of assignment.

还有一个问题是:并行赋值是运算符吗?

One more question is: Is parallel assignment an operator?

推荐答案

在 2 个单独的语句中进行赋值的问题是 i2 = i1 + i2 然后将使用 i1 而不是正确生成斐波那契数列所需的先前值.

The problem with doing the assignment in 2 separate statements is that i2 = i1 + i2 will then use the new value of i1 rather than the previous value required to correctly generate the Fibonacci sequence.

当您使用并行赋值时,首先计算右侧的所有表达式,然后将其分配给左侧的接收变量.

When you use parallel assignment all of the expressions on the right hand side are evaluated first and then assigned to the receiving variables on the left hand side.

并行赋值不是一个特殊的运算符.本质上,右侧是一个数组,如果我们在左侧列出多个变量,那么该数组将被解包并分配到相应的变量中.

Parallel assignment isn't a special operator. Essentially what is on the right hand side acts as an Array where if we list multiple variables on the left hand side then the array is unpacked and assigned into the respective variables.

以下是更多示例:

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]

这是 ruby​​ 的一个有用特性,例如它有助于拥有返回多个值的方法,例如

It is a useful feature of ruby, for example it facilitates having methods that return multiple values e.g.

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

sum, difference = sum_and_difference 5, 3

在 Java 中,最接近的方法是有一个返回 int[] 的方法,但是如果我们想返回一个字符串和一个数字,我们需要创建一个小 POJO 来充当结构体对于返回值或返回 Object[] 并用强制转换使代码混乱.请参阅我最近回答的另一个问题更实际的例子.

In Java the closest thing would be to have a method that returned int[] but if we wanted to return a string and a number we'd need to create a little POJO to act as struct for the return value or return Object[] and clutter the code up with casts. See this other question that I answered recently for a more practical example.

这篇关于Ruby 中的并行赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆