我认为 return 关键字在 Ruby 中是可选的,无论您是否请求它,您总是return.鉴于此,我发现 foo 和 bar 具有不同的输出,这是由 foo 包含显式的 return.
I thought the return keyword was optional in Ruby and that you are always returning whether you request it or not. Given that, I find it surprising that foo and bar have different output determined by the fact that foo contains an explicit return in Proc f.
有人知道为什么会这样吗?
Does anyone know why this is the case?
推荐答案Ruby 具有三种结构:
Ruby has three constructs:
Ruby 有三个从某事返回的关键字:
Ruby has three keywords that return from something:
在 lambdas 中,return 的行为类似于 next,无论出于何种原因.next 和 break 以它们的方式命名是因为它们最常用于像 each 这样的方法,其中终止块将导致迭代使用集合的 next 元素继续,终止 each 将使您中断退出循环.
In lambdas, return behaves like next, for whatever reason. next and break are named the way they are because they are most commonly used with methods like each, where terminating the block will cause the iteration to resume with the next element of the collection, and terminating each will cause you to break out of the loop.
如果您在 foo 的定义中使用 return,您将从 foo 返回,即使它在块或过程中.要从块返回,您可以改用 next 关键字.
If you use return inside the definition of foo, you will return from foo, even if it is inside a block or a proc. To return from a block, you can use the next keyword instead.
def foo f = Proc.new { next "return from foo from inside proc" } f.call # control leaves foo here return "return from foo" end puts foo # prints "return from foo"更多推荐
为什么显式返回对 Proc 有影响?
发布评论