block syntax difference causes “LocalJumpError: no block given (yield)” [duplicate]

安稳与你 提交于 2019-12-17 16:55:15

问题


Saw a strange case come up, trying to figure out what is happening here:

> def test
>   p yield
> end
=> nil
> test { 1 }
1
=> 1
> p test { 1 }
1
1
=> 1
> p test do
>   1
> end
LocalJumpError: no block given (yield)

回答1:


The parser recognizes this

p test do
  1
end

as this

(p test) do
  1
end

The block is passed to p, not test. Therefore, yield can't yield and raises that error.




回答2:


do and {} to denote blocks attached to methods are not completely interchangeable.

p test do
  1
end

Precedence is screwing with you. This is actually this:

p(test()) do
  1
end

So the block is getting passed to p, not test.

{} has higher precedence than do, and so binds more tightly to the syntactically closer method. This is also true for other ruby keywords that have symbolic equivalents, such as and/&& and or/||, which is why the symbols are usually recommended over the words.



来源:https://stackoverflow.com/questions/18623447/block-syntax-difference-causes-localjumperror-no-block-given-yield

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!