class Foo
def with_yield
yield(self)
end
def with_instance_eval(&block)
instance_eval(&block)
end
end
f = Foo.new
f.with_yield do |arg|
p self
# => main
p arg
# => #<Foo:0x100124b10>
end
f.with_instance_eval do |arg|
p self
# => #<Foo:0x100124b10>
p arg
# => #<Foo:0x100124b10>
end
Why does the second 'p arg
' report the Foo instance? Shouldn't it report nil
since with_instance_eval
does not yield self
to the block?
Apparently in ruby 1.8 instance_eval does not only change the value of self inside the block to its receiver, it also yields that value. In 1.9 this is no longer the case (arg will be nil there), so that behavior should not be relied upon (I'm also pretty sure it's undocumented).