2009-09-15 55 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會出現零),從而使行爲不應加以依賴(我也敢肯定,這是無證)。

相關問題