From: David Alan Black Date: 2001-08-18T20:48:36+09:00 Subject: [ruby-talk:19972] Re: problem understanding class relationships Hello -- On Sat, 18 Aug 2001, Yukihiro Matsumoto wrote: > Hi, > > In message "[ruby-talk:19960] problem understanding class relationships" > on 01/08/18, Tobias Reif writes: > > |Thus all classes are in the same family > |and thus @@ variables would be shared among all objects. > | > |Where am I erring? > > Like constants, class variables must be assigned at the class/module > top level, and shared among its subclasses. > > class Foo > @@foo = 43 # @@foo is assigned (declared) here. > end > > class Bar def bar > p @@foo # @@foo is available. > end > end > > class Baz def baz > p @@foo # @@foo is NOT available here. > end > end Another permutation -- sort of useless, but I found it interesting to see how this works: class A end # Assign to a class variable in a subclass *first*. class B < A @@cv = "in B" def cv; @@cv; end end a = A.new b = B.new puts b.cv # "in B" # Now go back and assign in the superclass. class A @@cv = "in A" def cv; @@cv; end end # Result: A and B