简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM