简体   繁体   中英

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:

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? (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. instance_eval gives you nothing "extra" here. But if you use it on an instance of a class, then you get different behaviour. Ie Foo1.new.instance_eval... .

See here for a good explanation:
How to understand the difference between class_eval() and instance_eval()?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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