From: "Christoph R." Date: 2003-09-17T23:33:46+09:00 Subject: Re: Class variables, module inclusion and instance_eval Tim Bates wrote: .... > irb(main):001:0> module Mod > irb(main):002:1> def self.append_features(aModule) > irb(main):003:2> super > irb(main):004:2> aModule.instance_eval do > irb(main):005:3* @@foo = aModule.name > irb(main):006:3> end > irb(main):007:2> end > irb(main):008:1> end > => nil > irb(main):009:0> class KlassA > irb(main):010:1> include Mod > irb(main):011:1> end > => KlassA > irb(main):012:0> class KlassB > irb(main):013:1> include Mod > irb(main):014:1> end > => KlassB > irb(main):015:0> class KlassA > irb(main):016:1> puts @@foo > irb(main):017:1> end > KlassB > => nil > > Somehow, even though the class variable is defined within the context of > the class (via instance_eval) it still gets shared, contrary to the > example of Exhibit B. This is frustrating me, because I want my library > to be able to define a class variable that belongs to only one class, > and I can't find a way to do it. Currently, I'm doing this: This has to do with Ruby's scoping rules - here is an example I changed ``append_feature'' to the more modern ``included'' --- module Mod def self.included(aModule) # the string version creates the expected # module aModule .. end # scope aModule.module_eval "@@foo = #{aModule.name}" end end class A include Mod end module Mod begin @@foo rescue NameError => mes puts mes end end class B include Mod end class A puts @@foo end ## your way module Nod def self.included(aModule) # scope of @@bar is module Nod ... end aModule.module_eval do @@bar = aModule.name end end end class A include Nod end module Nod puts "@@bar == #{@@bar} defined in #{self}" end class B include Nod end class A puts @@bar end --- results in --- uninitialized class variable @@foo in Mod A @@bar == A defined in Nod B --- /Christoph