Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I evaluate a block inside a Proc?

Can I yield a block inside a Proc? Consider this example:

a = Proc.new do
  yield
end

a.call do
  puts "x"
end

What I'm trying to achieve is to print x, but interpreting this with ruby 2.0 raises LocalJumpError: no block given (yield).

like image 624
fotanus Avatar asked Feb 16 '23 19:02

fotanus


1 Answers

No you can't, because the Proc you've created is an independent yield - that is, it's a yield that has no block in its context. Although you can call procs with specified parameters and thereby pass the parameters into the proc, yield doesn't work based on specified parameters; it executes the block found within the proc's closure. And the proc's closure is predefined; it is not modified just because you call it later with a block.

So it's equivalent of just typing 'yield' straight into irb (not within any method definitions) which returns the LocalJumpError: no block given (yield) error.

like image 84
Rebitzele Avatar answered Feb 23 '23 01:02

Rebitzele