简体   繁体   English

模块中class_eval和instance_eval的区别

[英]Difference between class_eval and instance_eval in a module

Code:代码:

module Mod1
  def self.included(base)
    base.class_eval do
      class << self
        attr_accessor :test
      end
      @test = 'test1'
    end
  end
end

module Mod2
  def self.included(base)
    base.instance_eval do
      class << self
        attr_accessor :test
      end
      @test = 'test2'
    end
  end
end

class Foo1
  include Mod1
end

class Foo2
  include Mod2
end

puts Foo1.test
puts Foo2.test

Output is: Output 是:

test1
test2

I realize one evaluates in the context of the class while the other evaluates in the context of the instance, but... in this case, why are they returning as such?我意识到一个在 class 的上下文中进行评估,而另一个在实例的上下文中进行评估,但是......在这种情况下,他们为什么会这样返回? (I'd have expected an exception in one or the other.) (我本以为其中一个会出现异常。)

In your example there is no difference.在您的示例中没有区别。

> Foo1.instance_eval { puts self } 
Foo1

> Foo1.class_eval { puts self }
Foo1

The instance of a class is the class itself. class 的实例是 class 本身。 instance_eval gives you nothing "extra" here. instance_eval在这里没有给你任何“额外”的东西。 But if you use it on an instance of a class, then you get different behaviour.但是,如果您在 class 的实例上使用它,那么您会得到不同的行为。 Ie Foo1.new.instance_eval... .Foo1.new.instance_eval...

See here for a good explanation:看到这里有一个很好的解释:
How to understand the difference between class_eval() and instance_eval()? 如何理解 class_eval() 和 instance_eval() 的区别?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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