|
Sibling rivalry and class variables: msg#01179lang.ruby.general
On Mon, Aug 12, 2002 at 02:05:45AM +0900, Kent Dahl wrote: > Because class variables are some kind of wierd black magic. Once a class > variable comes into existance, it is available to all instances of the > class and subclasses. I.e. it is available downwards in the inheritance > hierarchy. > > When you don't make the @@data variable until the subclass, it does not > propagate back up to the superclass. Beware, this path may lead to > madness: So I see... --- begin classvar.rb --- class Parent @@name = "I'm the parent." def initialize puts @@name end end class Son < Parent @@name = "I'm the son." end class Daughter < Parent @@name = "I'm the daughter." end Son.new # => I'm the daughter. Daughter.new # => I'm the daughter. --- end --- This behavior is downright counterintuitive to me. The class "Daughter" has managed to affect the behavior of the class "Son", but "Daughter" is not an ancestor of "Son". What would you guys suggest I do if I want a variable set in the parent that the child may or may not override? So far, I've had to resort to using instance variables instead, like this: class Parent def initialize @name = "I'm the parent." end end class Son def initialize super @name = "I'm the son." end end class Daughter def initialize super @name = "I'm the daughter." end end This doesn't seem to be the right way to do things though, since with the way I'm using @name, it's a variable whose value will be the same across all instances of the same class. Thoughts?
|
|
| <Prev in Thread] | Current Thread | [Next in Thread> |
|---|---|---|
| Previous by Date: | Re: Q) about singleton methods and access control, Kent Dahl |
|---|---|
| Next by Date: | Re: class === class often false, dblack |
| Previous by Thread: | Re: subclassing and @@variable, Kent Dahl |
| Next by Thread: | Re: Sibling rivalry and class variables, Kent Dahl |
| Indexes: | [Date] [Thread] [Top] [All Lists] |
| News | FAQ | advertise |