“返回”行为ruby 块中的关键字
有人可以解释以下行为:
def iterate
return yield
return "end of iterate"
end
def test_iterate
assert_equal( "end of iterate", iterate { return "end of block" } )
assert_equal( "end of block", iterate { "end of block" } )
end
我理解 Procs (这就是块)应该在它们被调用的范围内返回。 (与 lambda 不同)考虑到这一点,测试中的两个调用不应该返回“块结束”吗?
此测试通过“ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]”( OSX 10.6.7 )
Can someone explain the behavior of the following
def iterate
return yield
return "end of iterate"
end
def test_iterate
assert_equal( "end of iterate", iterate { return "end of block" } )
assert_equal( "end of block", iterate { "end of block" } )
end
I understand that Procs ( Which is what blocks are ) should return within the scope they are called. ( Unlike lambdas ) With this in mind, shouldn't both calls in the tests return "end of block"?
This test passes on 'ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]' ( OSX 10.6.7 )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
return 关键字从词法封闭方法返回。即*test_iterate*。
要以动态范围的方式从块返回特定值,您应该使用 break 关键字。
对于您的情况:
测试将失败。因为 iterate 方法的第二个 return 语句永远不会运行。
预期的语义应该通过使用异常来完成:
The return keyword returns from the lexicaly enclosing method. That is, *test_iterate*.
To return a certain value from a block in a dynamically scoped fashion, you should use the break keyword instead.
In your case:
The test will fail. because the second return statement of the iterate method will never run.
The intended semantics should be accomplished by using exceptions: