2009-09-15 57 views
1
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 

为什么第二个“p arg”报告中的富实例?难道不应该报告因with_instance_evalnil不会产生self到块?为什么第二个'p arg'报告Foo实例?

+0

嘿,那是从http://stackoverflow.com/questions/1425055/is-yield-self-the-same-as-instanceeval/1425600#1425600我的代码:) – 2009-09-16 06:51:11

回答

4

显然,在红宝石1.8 instance_eval的不仅改变块到其接收器内自身的价值,这也得到该值。在1.9这不再的情况下(ARG会出现零),从而使行为不应加以依赖(我也敢肯定,这是无证)。

相关问题