Have a parent class's method access the subclass's constants

前端 未结 5 886
闹比i
闹比i 2021-02-12 03:56

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         


        
5条回答
  •  不要未来只要你来
    2021-02-12 04:41

    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.
    • instances of class Animal may call the method make_noise.
    • class Dogdefines the constant NOISE with its value.
    • instances of Dog and the class Dog itself may use the constant NOISE.

    What is not possible:

    • Instances of 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:

    1. Define an abstract method in class Animal which defines that make_noise should be defined. See the answer https://stackoverflow.com/a/6792499/41540.
    2. Define in your concrete classes the method again, but now with the reference to the constant.

提交回复
热议问题