2012-07-02 38 views
1

我发现从instance_exec为什么instance_exec和class_exec具有不同的行为?

class KlassWithSecret 
    def initialize 
     @secret = 99 
    end 
    end 
    k = KlassWithSecret.new 
    k.instance_exec(5) {|x| @secret+x } #=> 104 
文档下面的代码execerpt

我为何instance_exec所做的就是下图中,其添加的@secret + 5的单例类的理解

+-----------------------+ 
    | singleton class do | 
    |  def method1  | 
    |  ...    | 
    |  end    | 
    |  ...    | 
    |  @secret + 5  | 
    | end     | 
    |      | 
    |      | 
    +-----------+-----------+ 
       | 
    +---------+-------+ 
    | instance k  | 
    | @secret  | 
    |     | 
    +-----------------+ 

于是我想出了代码中使用class_exec得到相同的结果

k.singleton_class.class_exec(5) {|x| @secret + x} 

它给我一个@secret是零误差,我想知道为什么是的,什么是错我的理解

更新:

我注意到k.instance_exec {}绑定和k.singleton_class.class_exec {}绑定有不同的结合对象,所以他们必须是不同的。我仍然想知道它们如何在引擎盖下工作

回答

1

instance_exec是用C编写的,c-api允许您指定执行方法时self的值。

在将它变成ruby之前,人们通过在singleton类中定义一个方法并调用它来实现它,而不是仅仅在singleton类的上下文中执行东西(您可以在activesupport 2.x中或在rspec_core的instance_eval_with_args

单例类的对象是在自己的权利的对象,所以有它自己的一套不与相应的对象共享实例变量的

相关问题