3

I want to pass a block to a block that is instance_eval-ed like this,

instance_eval(&block) { puts "test" }

where block is defined as containing something like:

puts "Incoming message:"
yield

Is this possible? I discovered a way of doing this with fibers, but I'm trying to use yield first. Looking at this question, it looks like this might not be possible, but I wanted to confirm.

Community
  • 1
  • 1
Max
  • 4,882
  • 2
  • 29
  • 43
  • 1
    Can you elaborate a bit more as to what you're trying to do? It's not really clear. Also your example is passing two blocks to `instance_eval`, which makes no sense. – Andrew Marshall Jan 05 '13 at 02:15
  • You want that `yield` to yield to your `{ puts "test" }` block? – mu is too short Jan 05 '13 at 02:25
  • You're right, it doesn't make sense in that it's not actually valid, but I want the second block to be passed to the block that instance_eval is actually evaluating, so the final output would be "Incoming message:\ntest". I'm looking for something that works similarly but _is_ valid, of course. – Max Jan 05 '13 at 06:19

1 Answers1

4

It's weird, indeed. Why instance_eval ? It's usually used to change self, and evaluate in the context of the receiver.

cat = String.new('weird cat')

block1 = lambda do |obj, block|
    puts "Incoming message for #{obj}:"
    block.call
end

block2 = Proc.new { puts "test" }

block3 = lambda {|obj| block1.call(obj, block2)}

cat.instance_eval(&block3)

Execution (Ruby 1.9.2) :

$ ruby -w t2.rb 
Incoming message for weird cat:
test
BernardK
  • 3,674
  • 2
  • 15
  • 10