我无法弄清楚n.times
行如何在下面给出的ruby代码中工作,特别是逗号的含义以及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中的fibonacci序列的问题时给出的代码,在此stackoverflow问题:Ruby Fibonacci algorithm。
我不明白街区内发生了什么。
答案 0 :(得分:2)
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
答案 1 :(得分:2)
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
。