From: Jeremy Henty Date: 2006-02-02T06:58:31+09:00 Subject: Re: question about class variables and instance variables On 2006-01-31, Eric Hodel wrote: > class variables are shared between a class, its instances, its > subclasses and its subclass instances. Is this really the whole story? Because until now I always thought I didn't understand class variables but if this is so then now I do. Wheeeee! But there's at least one gotcha; a class variable shadows any class variable of the same name that you subsequently create in an ancestor class: $ irb irb(main):001:0> class A ; end ; class B < A ; end => nil irb(main):002:0> class B ; @@x = 1 ; end ; class A ; @@x = 0 ; end => 0 irb(main):003:0> class A ; puts @@x ; end ; class B ; puts @@x ; end 0 1 => nil irb(main):004:0> exit .... but if you create the class variable in the ancestor class first then the descendant class inherits it instead of creating a new one: $ irb irb(main):001:0> class A ; end ; class B < A ; end => nil irb(main):002:0> class A ; @@x = 0 ; end ; class B ; @@x = 1 ; end => 1 irb(main):003:0> class A ; puts @@x ; end ; class B ; puts @@x ; end 1 1 => nil irb(main):004:0> exit Any other subtleties? Cheers, Jeremy Henty