def foo
f = Proc.new { return "return from foo from inside proc" }
f.call # control leaves foo here
return "return from foo"
end
def bar
b = Proc.new { "return from bar from inside proc" }
b.call # control leaves bar here
return "return from bar"
end
puts foo # prints "return from foo from inside proc"
puts bar # prints "return from bar"
我認爲return
關鍵字在Ruby中是可選的,並且無論您是否要求,您總是return
。鑑於此,我發現令人驚訝的是foo
和bar
具有不同的輸出,這由foo
在Proc f
中包含明確的return
這一事實確定。爲什麼明確的回報會影響Proc?
有誰知道這是爲什麼?
編輯也提到了lambda的行爲 – sepp2k 2009-09-17 08:49:45
注意,在你的例子中,如果下一個被省略,行爲依然存在。 – 2009-09-17 09:17:44
順便說一句,我認爲我們都做了很好的工作來回答一個不同的問題:)至於爲什麼,我認爲只有馬茨知道,關於閉包的很多東西違反了最少驚喜的原則。 – 2009-09-17 09:33:30