为什么显式返回会对 Proc 产生影响? [英] Why does explicit return make a difference in a Proc?
问题描述
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
包含显式 return
Proc f
中的代码>.
I thought the return
keyword was optional in Ruby and that you are always return
ing 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:
- block 不是对象,而是由
{
...}
或do
...结束
. - proc 是由
Proc.new
或proc
创建的Proc
对象. - lambda 是由
lambda
(或 Ruby 1.8 中的proc
)创建的Proc
.
- A block is not an object and is created by
{
...}
ordo
...end
. - A proc is a
Proc
object created byProc.new
orproc
. - A lambda is a
Proc
created bylambda
(orproc
in Ruby 1.8).
Ruby 有三个从某事物返回的关键字:
Ruby has three keywords that return from something:
return
终止它所在的方法或 lambda.next
终止它所在的块、proc 或 lambda.break
终止产生块或调用它所在的 proc 或 lambda 的方法.
return
terminates the method or lambda it is in.next
terminates the block, proc, or lambda it is in.break
terminates the method that yielded to the block or invoked the proc or lambda it is in.
在 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 产生影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!