我无法弄清楚下面给出的 ruby 代码中n.times
行是如何工作的,特别是逗号的含义以及 new
变量是如何更新的。
def fib(n)
raise "fib not defined for negative numbers" if n < 0
new, old = 1, 0
n.times {new, old = new + old, new}
old
end
该代码有效,并且是用户 pjs 在回答有关 ruby 中斐波那契数列的问题时给出的代码,在这个堆栈溢出问题中:Ruby 斐波那契算法。
我不明白街区里面发生了什么。
Ruby 支持并行赋值。
new, old = new + old, new
大致相当于:
temp = [new + old, new] # right side are evaluated and stored in an array
new, old = temp # there is a commaa in the left side
# so they get the value from the array, one by one
n.times { ... }
会做n
次块内的任何事情。 例如,如果n
是5
,则等效于:
new, old = 1, 0
new, old = new + old, new # new = 1+0 = 1; old = 1
new, old = new + old, new # new = 1+1 = 2; old = 1
new, old = new + old, new # new = 2+1 = 3; old = 2
new, old = new + old, new # new = 3+2 = 5; old = 3
new, old = new + old, new # new = 5+3 = 8; old = 5
old
# => 5
另一件可能让您感到困惑的事情是并行分配:
new, old = new + old, new
一般来说,您可以拥有:
a, b = <some-expr>, <some-other-expr>
将首先计算右侧的表达式,然后a
分配第一个值b
第二个值。 您可以使用它作为交换两个变量的快速方法,而无需使用temp
变量,例如:a, b = b, a
。