Can I evaluate a block inside a Proc?
Asked Answered
C

2

3

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).

Colver answered 23/7, 2013 at 18:27 Comment(0)
A
3

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.

Ankylosis answered 23/7, 2013 at 18:56 Comment(0)
S
3

@Rebitzele has explained why your code doesn't work: the yield keyword is shorthand notation for calling an anonymous block that has been passed to a method, and in this case there isn't even a method.

But you can of course give the block a name and then call it like you would call any other callable object:

a = ->&block { block.() }

a.() do puts 'x' end
# x
Sabelle answered 23/7, 2013 at 22:11 Comment(1)
Still trying to figure out what's going on here, but this doesn't seem to work for me: obj.instance_eval { def wrap(&block); a = ->&block { block.() }; a.() { puts 'goodbye' }; end}; obj.wrap { puts 'hello'; yield } will only print goodbyeDeledda

© 2022 - 2024 — McMap. All rights reserved.