Can I transfer a block to Proc?

I am wondering if it is possible to pass a block to Proc. Just passing a block to Proc.call does not work:

 foo = Proc.new { yield } foo.call { puts "test" } 

Results in:

LocalJumpError: no block (exit)

The same thing happens with lambdas. However, this one works with method objects:

 class Foo def bar yield end end bar = Foo.new.method :bar bar.call { puts "Success!" } 

Results in:

Success!

It is strange that it still works after converting the method object to proc:

 bar.to_proc.call { puts "Success!" } 

Results in:

Success!

So why is a Proc that was made from a block not accepting blocks, but a Proc that was originally a method? Is it possible to create Procs from blocks that accept blocks?

+7
ruby
source share
1 answer

Procs cannot accept blocks as implicit arguments (the format you are trying to). Proc can accept other proc objects as arguments, explicitly or using arguments. Example:

 a = Proc.new do |&block| block.call end a.call() {puts "hi"} 

yield is a bit of lagoon-level magic that only works in the context of a method.

+5
source share

All Articles