【问题标题】:Ruby: why do while and until not return last line they execute from a function?Ruby:为什么 while 和 until 不返回它们从函数执行的最后一行?
【发布时间】:2014-10-10 14:17:03
【问题描述】:

我希望 while 循环返回它执行的最后一条语句,但函数似乎没有返回它。

(1)这似乎有效..

[10] pry(main)> counter = 0
=> 0
[11] pry(main)> a = counter+=1 while counter < 10
=> nil
[12] pry(main)> a
=> 10

(2) 这不像我预期的那样工作。我希望返回 10 并将其存储到 b

[19] pry(main)> def increment(terminal_value)
[19] pry(main)*   counter = 0  
[19] pry(main)*   while counter < terminal_value
[19] pry(main)*     counter+=1
[19] pry(main)*   end  
[19] pry(main)* end  
=> :increment
[20] pry(main)> b = increment(10)
=> nil
[21] pry(main)> b
=> nil

问题:

  • 为什么在 (1) 中,nil 会从赋值语句中返回?
  • 为什么b 没有被分配10

更新:

正如@DaveNewton 提到的,在(1)中,我以为我在做:

a = (counter +=1 while counter < 10)

但我实际上是这样做的:

(a = counter +=1) while counter < 10

【问题讨论】:

  • 你在做不同的事情。 (1) 得到一个nil 并显示它,(2) 也是如此。在 (1) 中,您正在递增一个局部变量 counter,并显示它。在(2)中设置了一个局部变量b调用increment的返回结果,即nil
  • 哇。感谢@DaveNewton 的花絮!

标签: ruby


【解决方案1】:

在您的两个示例中,while 循环结果为 nil

来自while loop

除非break 用于提供值,否则while 循环的结果是nil

until 也一样:

就像while 循环一样,until 循环的结果是nil,除非使用了break

【讨论】:

  • @KubaSub a 具有赋值 counter+=1 的值,而不是 while 循环。
【解决方案2】:

补充于浩的答案是this问题的答案

ruby 中的任何语句都返回最后一个计算表达式的值。

如果您将代码更改为,请遵循该逻辑(不是说这是好的做法或纵容它,只是一个示例):

def increment(terminal_value)
  counter = 0  
    while counter < terminal_value
      counter+=1
    end
  counter
end

b = increment(10)

它将输出 10。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    相关资源
    最近更新 更多