Block Syntax Difference Causes "Localjumperror: No Block Given (Yield)"

block syntax difference causes LocalJumpError: no block given (yield)

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.

Passing arguments to around_action raises: LocalJumpError no block given (yield)

I ended up solving it with:

around_action -> (controller, block) { do_stuff("foo", block) }

def do_stuff(arg, block)
some_block do
Rails.logger.error "arg: #{arg}"
block.call
end
end

LocalJumpError: no block given (yield) rails console

You can use yield only when you are inside a method which has been called with a block. In the rails console, you are in the main environment and without any block which is why you get that error.

You can take a look at this answer to find out how yield works in the view.

The best way to do what you're trying to do is to put a debugger inside the view while its rendering and then test out the provided functionality.

Why does Ruby evaluate these two expressions differently? The only difference is {...} and do...end

Precedence matters. {} has a higher precedence over method call. do-end has a lower precedence.

pp [1, 2, 3].map { |r| r + 1 }

is parsed as pp ([1, 2, 3].map { |r| r + 1 }), which is:

pp([1, 2, 3].map { |r| r + 1 })

pp [1, 2, 3].map do |r| r + 1 end

is parsed as (pp [1, 2, 3].map) do |r| r + 1 end, which is:

pp([1, 2, 3].map, &->(r){ r + 1 })

In the latter case passing block to pp is a NOOP.

Block not called in Ruby

Add parentheses to puts

puts(m do
x = 2
y = 3
x * y
end)

The output is 6.

Your code is equivalent to

puts(m) do 
x = 2
y = 3
x * y
end

What is the difference or value of these block coding styles in Ruby?

The rails team and many other rubyists prefer to use curly braces for one line blocks and do...end for multi-line ones.

The only functional difference between the two is that the precedence of a do...end block is lower than that of a {...} block.

Code block passed to each works with brackets but not with 'do'-'end' (ruby)

puts mystring.gsub(art[0]).each do
art[1][rand(art[1].length) -1]
end

Here you called puts without parens, the do ... end refers to the puts method, that does nothing with a block and prints mystring.gsub(art[0]).each (with is a Enumerator).

The { ... } is called with the nearest method. Becomes ugly, but you can do it with do ... end:

puts(mystring.gsub(art[0]).each do
art[1][rand(art[1].length) -1]
end)

Or, better, put the result in a variable and print the variable:

var = mystring.gsub(art[0]).each do
art[1][rand(art[1].length) -1]
end
puts var

Anyway, the each don't changes the object, it just iterate and returns the object itself. You may be wanting the map method, test it.



Related Topics



Leave a reply



Submit