为什么显式返回对 Proc 有影响?

编程入门 行业动态 更新时间:2024-10-09 07:19:29
本文介绍了为什么显式返回对 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.

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:

  • block 不是对象,而是由 { ... } 或 do ... end.
  • proc 是由 Proc.new 或 proc 创建的 Proc 对象.
  • lambda 是由 lambda(或 Ruby 1.8 中的 proc)创建的 Proc.
  • A block is not an object and is created by { ... } or do ... end.
  • A proc is a Proc object created by Proc.new or proc.
  • A lambda is a Proc created by lambda (or proc in Ruby 1.8).
  • Ruby 有三个从某事返回的关键字:

    Ruby has three keywords that return from something:

  • return 终止它所在的方法或 lambda.
  • next 终止它所在的块、过程或 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 有影响?

    本文发布于:2023-11-23 13:19:27,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1621584.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:有影响   Proc

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!