mowienay mowienay -5 years ago 134
Ruby Question

Why can't we pass a {} block with other parameters to a method in Ruby

When passing a block to a method in ruby with other parameters, why do we have to do it like that

def method4(condition, attribute, &block)
return "No Block" if block.nil?
if condition
puts attribute

method4(true,4) do
puts "Hello World"

While we can't do it like that

method4(true,4,{puts "Hello World"})

Apparently the latter is syntactically wrong

Answer Source

You can only pass other objects as arguments, and blocks are not objects in Ruby. Blocks are syntactic constructs.

But they can easily be wrapped in objects, objects of Proc class. There is even a special shorthand operator for that:

method4(true, 4, &->{puts 'Hello World'})

A short explanation of above code:

->{} creates a Proc object around given block. As method4 requires a block, and not an object, you need to "unwrap" it to block once more, and that's why ampersand is there. If the signature of method4 were instead:

def method4(condition, attribute, proc) # note no ampersand

you would be able to omit the ampersand in method call too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download