为什么while修饰符与块的行为不同?

时间:2015-05-24 18:05:37

标签: ruby

irb(main):186:0* begin puts "abc" end while false
abc
=> nil
irb(main):187:0> puts "abc" while false
=> nil

因此,当您使用带有while修饰符的块时,该块将被执行一次(这似乎是许多其他语言中的do-while循环)。但是如果你使用带有while修饰符的单个语句,那么它就更像是一个while循环,首先检查条件。这有点令人惊讶,为什么这种行为存在?

3 个答案:

答案 0 :(得分:1)

我认为你的困惑在于begin/end is not considered a block。要用块来展示你的例子,请看一下:

[3] pry(main)> loop { puts "hi" } while false
=> nil

答案 1 :(得分:1)

同时确保至少一次执行,但第二次不是一次,是红宝石的许多辛辣糖之一。它相当于

while false
  puts 'abc'
end

记住

puts 'abc' if false

两者都行为正确。

答案 2 :(得分:1)

This seems to be just a quirk of the language. ... while condition acts a a statement modifier except when it is after a begin ... end, where it behaves like a do ... while loop from other languages.

Yukihiro Matsumoto (Matz, the creator of Ruby) has said he regrets this, and would like to remove this behaviour in the future if possible.

There’s a bit more info in this blog post from New Relic, where I found the link to the mail list post: https://blog.newrelic.com/2014/11/13/weird-ruby-begin-end/