Search code examples
rubyblock

How can I pass a block to an `instance_eval`-ed block?


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.


Solution

  • 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