为什么显式返回对 Proc 有影响? [英] Why does explicit return make a difference in a Proc?

查看:36
本文介绍了为什么显式返回对 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.鉴于此,我发现 foobar 具有不同的输出,这是由 foo 包含显式的 returnProc f 中的代码>.

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:

  1. block 不是对象,而是由 { ... }do ... end.
  2. proc 是由 Proc.newproc 创建的 Proc 对象.
  3. lambda 是由 lambda(或 Ruby 1.8 中的 proc)创建的 Proc.
  1. A block is not an object and is created by { ... } or do ... end.
  2. A proc is a Proc object created by Proc.new or proc.
  3. A lambda is a Proc created by lambda (or proc in Ruby 1.8).

Ruby 有三个从某事返回的关键字:

Ruby has three keywords that return from something:

  1. return 终止它所在的方法或 lambda.
  2. next 终止它所在的块、过程或 lambda.
  3. break 终止产生块或调用它所在的 proc 或 lambda 的方法.
  1. return terminates the method or lambda it is in.
  2. next terminates the block, proc, or lambda it is in.
  3. break terminates the method that yielded to the block or invoked the proc or lambda it is in.

在 lambdas 中,return 的行为类似于 next,无论出于何种原因.nextbreak 以它们的方式命名是因为它们最常用于像 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆