rubyblockproc

Can I pass a block which itself expect a block to instance_exec in ruby?


I expect the code

foo=proc{puts "foo"}

instance_exec(1,2,3,&foo) do |*args , &block|
  puts *args
  block.call
  puts "bar"
end

to output

1
2
3
foo
bar

But got the error

both block arg and actual block given

Can I pass a block which itself expect a block to instance_exec in ruby?


Solution

  • &foo tries to pass foo as a block to instance_exec, and you are already passing an explicit block. Omitting ampersand sends foo just like any other argument (except that it is a Proc instance). So, try this instead:

    instance_exec(1,2,3,foo) do |*args, block|
      puts *args
      block.call
      puts "bar"
    end
    

    This also means that you can do something like:

    bar = proc{ |*args, block|
      puts *args
      block.call
      puts "bar"
    }
    
    instance_exec(1,2,3,foo,&bar)
    

    And get the same result.

    More info at Difference between block and &block in Ruby