From: Artur Merke Date: 2006-10-17T22:00:12+09:00 Subject: Re: metaprogramming surprise? Jan Svitok schrieb: > On 10/17/06, Artur Merke wrote: > > Here comes some simple meta code > > > > >>>>>>>>>>>>>>>>>>>>>>>>> > > class D > > @@e=5 > > @@f = 10 > > @@g = 20 > > class << self > > attr_reader :e > > attr_accessor :g > > end > > def self.f > > @@f > > end > > > > def show > > print "\nshow @@e=",@@e, " @@f=", @@f, " @@g=",@@g > > print "\nshow self.class.e=", self.class.e > > print "\nshow self.class.f=", self.class.f > > print "\nshow self.class.g=", self.class.g > > end > > end > > > > D.g= 40 > > print "\nD.e= ",D.e > > print "\nD.g= ",D.g > > print "\nD.f= ",D.f > > D.new.show > > <<<<<<<<<<<<<<<<<<<<<<<<<<< > > > > here is the result > > > > D.e= nil > > D.g= 40 > > D.f= 10 > > show @@e=5 @@f=10 @@g=20 > > show self.class.e=nil > > show self.class.f=10 > > show self.class.g=40 > > > > I'would expect > > D.e= 5 > > D.g= 40 > > D.f= 10 > > show @@e=5 @@f=10 @@g=40 > > show self.class.e=nil > > show self.class.f=10 > > show self.class.g=40 > > > > so what's wrong with my understanding, that > > > > class D > > @@e=5 > > class << self > > attr_reader :e # <- why this does not refer to @@e > > end > > end > > There's a difference between class variables (@@x) and singleton class > instance variables (self.class.@x). They are not the same thing. OK, but why are they not the same??? I'm missing some kind of analogy, see the following code: >>>>>>>>>>>>>>>>>>> class E def show; print "\noutput @e= ",@e; end end class F def show; print "\noutput @@ff= ",@@ff; end end obj= E.new class << obj attr_accessor :e end class << F attr_accessor :ff end F.ff= "should be @@ff?, but is not" obj.e= "should be @e, and really is" obj.show F.new.show output @e= should be @e, and really is test.rb:33:in `show': uninitialized class variable @@ff in F (NameError) from test.rb:50