From: "Wolfgang Nádasi-Donner" Date: 2005-03-15T22:57:53+09:00 Subject: Re: [newby] class variables and class instance variable? -- Wolfgang N�dasi-Donner wonado@donnerweb.de "Lionel Thiry" schrieb im Newsbeitrag news:4232ff57$0$30162$ba620e4c@news.skynet.be... > Hello. > > class Test > @a = "value" > > def self.a > @a > end > > def initialize > @@a = "value2" > end > > def a > @@a > end > end > > puts Test.a # output: value > puts Test.new.a # output: value2 > > I don't understand (and I'm quite surprised), what is the difference in terms of > OO design between class variables, the @@a in the example above, and class > instance variables, the @a in the example? > > Thanks in advance, > Lionel Thiry The class variable ("@@") belongs to the class object, while the instance variable (@) belongs to the instanciated object. A short example. May be you want to count how many objects are created based on a class. If you want to avoid global variables ($), which is a very good decision, you can use class variables. Using instance variables will not work. >>>>> Example >>>>> class Mytest @@n_of_Mytest = 0 def initialize @@n_of_Mytest += 1 end def Mytest.n_of_Mytest @@n_of_Mytest end end puts Mytest.n_of_Mytest a = Mytest.new puts Mytest.n_of_Mytest b = Mytest.new c = Mytest.new puts Mytest.n_of_Mytest d = Mytest.new e = Mytest.new f = Mytest.new puts Mytest.n_of_Mytest >>>>> Output >>>>> 0 1 3 6 >>>>> End of Example >>>>> O.K.?