4

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.)

Denis de Bernardy
  • 75,850
  • 13
  • 131
  • 154

1 Answers1

4

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. I.e. Foo1.new.instance_eval ....

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

Community
  • 1
  • 1
Casper
  • 33,403
  • 4
  • 84
  • 79