For example:
class Animal
def make_noise
print NOISE
end
end
class Dog < Animal
NOISE = \"bark\"
end
d = Dog.new
d.make_noise # I want this to p
I think you have the wrong concept here. Classes in Ruby are similar to classes in Java, Smalltalk, C#, ... and all are templates for their instances. So the class defines the structure and the behavior if its instances, and the parts of the structure and behavior of the instances of its subclasses but not vice versae.
So direct access from a superclass to a constant in a subclass is not possible at all, and that is a good thing. See below how to fix it. For your classes defined, the following things are true:
class Animal defines the method make_noise.class Animal may call the method make_noise.class Dogdefines the constant NOISE with its value.Dog and the class Dog itself may use the constant NOISE.What is not possible:
Animal or the class Animal itself have access to constants of the class Dog.You may fix that by the following change:
class Animal
def make_noise
print Dog::NOISE
end
end
But this is bad style, because now, your superclass (which is an abstraction about Dog and other animals) knows now something that belongs to Dog.
A better solution would be:
Animal which defines that make_noise should be defined. See the answer https://stackoverflow.com/a/6792499/41540.