此块如何适用于整数乘以方法

  • 本文关键字:方法 整数 适用于 ruby
  • 更新时间 :
  • 英文 :


我无法弄清楚下面给出的 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次块内的任何事情。 例如,如果n5,则等效于:

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

最新更新