I have a related question - a similar problem to the one just given,
but that solution doesn’t fit here because I don’t just want the class
name - I want an attribute associated with the class, which subclasses
I’ve tried doing this using class variables, but it doesn’t work:
@@sound = “nothing”
"I say " + @@sound
class Cat < Animal
@@sound = “miaow”
class Dog < Animal
@@sound = “woof”
fudge = Cat.new()
tip = Dog.new()
This is an abstraction of my real situation but it captures the
essense: each subclass has some attribute which needs to be
manipulated at some point; the code to manipulate the attribute is
common across all subclasses, so it should live in the superclass.
(In fact, ideally, Animal is “abstract” and I don’t want to declare a
@@sound there at all - but if I do that, to_s complains about
“uninitialized class variable”.)
[[email protected] learn] ruby -v subclass_names.rb
ruby 1.8.4 (2005-12-24) [i386-freebsd6]
subclass_names.rb:9: warning: already initialized class variable @@sound
subclass_names.rb:13: warning: already initialized class variable
I say woof
I say woof
So I guess I’m misusing class variables.
I also tried it with constants (which would be even better since the
value won’t ever change) but got “I say nothing” twice instead.
If anyone can help me understand what’s going on and how this should
be done, I’d be grateful. I’m still thinking in python a bit too
much, I think.