I have a little question on passing block.
def a_method(a, b)
a + yield(a, b)
end
This works fine.
k = a_method(1, 2) do |x, y|
(x + y) * 3
end
puts k
But this won’t work.
puts a_method(1, 2) do |x, y|
(x + y) * 3
end
# LocalJumpError: no block given (yield)
Can anyone kindly explain this to me?
Thanks. Example taken from Metaprogramming Ruby by Paolo Perrotta. Great book.
The difference between
do .. endand curly braces is that the curly braces bind to the rightmost expression, whiledo .. endbind to the leftmost one. Observe the following examples:In the first case, the block made with
do..endwill be bound to the first function (leftmost). In the second case the block made with curly brackets will be bound to the second function (rightmost).Usually it’s good idea to use parentheses if you have two functions and a block – just for readability and to avoid mistakes.
It’s very easy to accidentally pass a block to
putsmethod, just as in your question.