Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

proc

block

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?

like image 611
benjaminchanming Avatar asked Mar 12 '13 09:03

benjaminchanming


1 Answers

&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

like image 188
Mladen Jablanović Avatar answered Nov 12 '22 22:11

Mladen Jablanović