为什么 ruby​​ 中的 break 语句在使用 Proc.new 与 & 符号时表现不同? [英] Why does the break statement in ruby behave differently when using Proc.new v. the ampersand sign?

查看:49
本文介绍了为什么 ruby​​ 中的 break 语句在使用 Proc.new 与 & 符号时表现不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

块的 break 语句(根据

The break statement for blocks (as per The Ruby Programming Language) is defined as follows:

它导致块返回到它的迭代器,迭代器返回到调用它的方法.

it causes the block to return to its iterator and the iterator to return to the method that invoked it.

因此,当运行以下代码时,会导致 LocalJumpError.

Therefore when the following code is run, it results in a LocalJumpError.

def test
    puts "entering test method"
    proc = Proc.new { puts "entering proc"; break }
    proc.call # LocalJumpError: iterator has already returned
    puts "exiting test method"
end
test

虽然以下代码不会抛出 LocalJumpError.&符号有什么特别之处?&符号不是隐式使用 Proc.new 吗?

While the following code does not throw a LocalJumpError. What is special about the ampersand sign? Doesn't the ampersand sign implicitly use Proc.new?

def iterator(&proc)
    puts "entering iterator"
    proc.call # invoke the proc
    puts "exiting iterator" # Never executed if the proc breaks
end

def test
    iterator { puts "entering proc"; break }
end
test

换句话说,我将 & 符号作为内联 Proc.new 调用的一种方式.此时行为应该与第一个代码片段相同.

In other words, I read the ampersand sign as a means of in-lining the Proc.new call. At which point the behavior should be just the same as the first code snippet.

def iterator (p = Proc.new { puts "entering proc"; break})
...
end

免责声明:我是学习语言(ruby 1.9.2)的新手,因此希望得到参考资料和详细的概要.

Disclaimer: I am newb learning the language (ruby 1.9.2), and therefore will appreciate references and a detailed synopsis.

推荐答案

break 使块成为块返回的调用者.在以下代码中:

break makes the block and the caller of the block return. In the following code:

proc = Proc.new { break }

转换为 Proc 对象的块的调用者"是 Proc.new.break 应该让块的调用者返回,但 Proc.new 已经返回.

The "caller" of the block which is converted to a Proc object is Proc.new. break is supposed to make the caller of the block return, but Proc.new has already returned.

在这段代码中:

def iterator(&b); b.call; end
iterator { break }

块的调用者是iterator,所以它使iterator返回.

The caller of the block is iterator, so it makes iterator return.

这篇关于为什么 ruby​​ 中的 break 语句在使用 Proc.new 与 & 符号时表现不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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