From: German Monfort Date: 2007-05-01T10:32:31+09:00 Subject: Re: Class Level Variables El Lunes, 30 de Abril de 2007 19:15, Gary Wright escribi�: > On Apr 30, 2007, at 1:52 PM, German Monfort wrote: > >> 2) Class variables are associated with a class *and* its subclasses > >> and the order of initialization is important. > >> > >> class C > >> @@foo = 42 # shared by C and its decendents! > >> def foo > >> @@foo # shared with C, D, and E > >> end > >> def bar > >> @@bar # this is C's @@bar > >> end > >> end > >> > >> class D < C > >> end > >> > >> class E < C > >> @@foo = 43 # @@foo shared with C, D, and E > >> @@bar = 44 # @@bar only defined for E > >> def bar > >> @@bar # this is E's @@bar > >> end > >> end > >> > >> puts D.new.foo # 43 > >> > >> puts E.new.bar # 44 > >> puts C.new.bar # undefined! > >> > >> class C > >> @@bar = 45 > >> end > >> > >> puts C.new.bar # 45 > >> puts E.new.bar # still 44 > >> > >> Gary Wright > > > > Shouldn't be > > puts D.new.foo # 42 ? > > > > Because D < C and has no foo method defined (so it uses C' foo) and > > also has > > no @@foo defined (so it uses C's @@foo) which is set to 42 not 43. > > I'm confused here. > > I was illustrating the fact that C and E don't share the same @@bar > due to > initialization order and the location of the definitions of C.bar and > E.bar. > > If you called D.new.foo you would get 43 because @@foo is shared by > C, D, and E > and was updated to reference 43 in the class block that defined E. > > If you called D.new.bar you would get 45 because the call to 'bar' > would be > implemented by the definition in C where @@bar refers to C's @@bar. > This is > a good example of how class variables are not relative to self! > > Gary Wright OK, I now understand the difference. Probably I'm too new to programming to understand the full power of class variables, and I found this concept a little bit dangerous because you can affect the whole behavior of a class by simply changing a class variable in any other subclass ... so I try not to use class variables for noiw. I still need to read more and more :D Thanks Gary