分配begin-end-while块的结果可防止块被执行

时间:2014-03-26 12:19:22

标签: ruby

您可以将块的结果分配给变量:

a = begin
  1
end
a #=> 1

同时,while可以在这样的块之后追加:

begin
  puts "this will be printed once"
end while false

它将至少执行一次。如果为该being-end-while块分配变量,则不再执行该变量:

a = begin
  puts "this won't be printed at all"
end while false

有人可以解释一下这里发生了什么吗?

1 个答案:

答案 0 :(得分:3)

如果添加作业,则会将其解释为:

(a = begin
  puts "this won't be printed at all"
end) while false

如何在begin ... end while false附近放置括号?

a = (begin
  puts "this won't be printed at all"
end while false)
# prints: this won't be printed at all
# a => nil