On Apr 29, 2007, at 8:44 PM, zswu wrote:
If you know C++.
@foo seams look link a normal member variable , i.e. private TYPE foo
@@foo seams look link a static member variable, i.e. static TYPE foo
I think a lot of confusion about Ruby class variables comes from
trying to compare them to similarly named constructs in other languages.
There is also a tendency to think class variables are like instance
variables because @@ is like @. Again, you’ll be mislead by that
- Class variables are lexically scoped. They are not associated
with the object identified by ‘self’ but instead by the innermost
@@foo = 42 # @@foo for A
@@foo # @@foo for A
@@foo # self is B but @@foo is for A
puts A.new.foo # 42
puts B.foo # 42
This lexical scoping is really important to understand when you
start using singleton class blocks, class_eval, module_eval,
or define_method, since the these constructs don’t introduce a lexical
@@foo = 42
@@foo = 43
puts @@foo # 43, this is Y’s @@foo, not X’s @@foo
- Class variables are associated with a class and its subclasses
and the order of initialization is important.
@@foo = 42 # shared by C and its decendents!
@@foo # shared with C, D, and E
@@bar # this is C’s @@bar
class D < C
class E < C
@@foo = 43 # @@foo shared with C, D, and E
@@bar = 44 # @@bar only defined for E
@@bar # this is E’s @@bar
puts D.new.foo # 43
puts E.new.bar # 44
puts C.new.bar # undefined!
@@bar = 45
puts C.new.bar # 45
puts E.new.bar # still 44
Initialize the class variable in the constroctor is a good idea.
That’s will make the class variable valide all of the class.
@@foo = XXXXX
This is a really bad idea. Every time you create a new instance,
you’ll reset the class variable.