Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

block

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)
like image 542
Brian Armstrong Avatar asked Sep 04 '13 20:09

Brian Armstrong


2 Answers

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.

like image 195
Sergio Tulentsev Avatar answered Sep 17 '22 11:09

Sergio Tulentsev


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.

like image 41
Alex Wayne Avatar answered Sep 20 '22 11:09

Alex Wayne