methods can take exactly one block, sort of like a special argument.
def foo yield 123 end foo { |x| puts x }
Notice how this method accepts null arguments, but still accepts a block. This is because this block suspension syntax using a method is a special case. Any block passed to a method can be started with the yield keyword. And you can even ask if the block with the block_given? keyword block_given? .
If you want to write it in a local variable, you can do this using special syntax.
def foo(a, &block) block.call a end foo(123) { |x| puts x }
In this case, you commit the block argument explicitly, with the & prefix in the argument list. Now you have a variable for this block, which you can send a call message to execute. Just be aware that this should appear at the end of the argument list.
Also pay attention to parens. foo(123) { |x| puts x } foo(123) { |x| puts x } . The argument list is stopped, the parsers are closed, and the attached block appears after. Again, because this is a special case in the syntax.
source share