gpt4 book ai didi

ruby-on-rails - 为什么 ruby​​ 中的 break 语句在使用 Proc.new 和符号时表现不同?

转载 作者:数据小太阳 更新时间:2023-10-29 06:58:34 25 4
gpt4 key购买 nike

block 的 break 语句(根据 The Ruby Programming Language )定义如下:

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

因此,当运行以下代码时,会导致 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 吗?

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 调用的一种方式。此时的行为应该与第一个代码片段相同。

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

免责声明:我是学习该语言(ruby 1.9.2)的新手,因此希望能提供引用资料和详细的概要。

最佳答案

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

proc = Proc.new { break }

转换为 Proc 对象的 block 的“调用者”是 Proc.new。 break 应该让 block 的调用者返回,但 Proc.new 已经返回。

在这段代码中:

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

block 的调用者是iterator,所以它让iterator返回。

关于ruby-on-rails - 为什么 ruby​​ 中的 break 语句在使用 Proc.new 和符号时表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8888958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com