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

前端 未结 5 818
闹比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:16

    I think that you don't really want a constant; I think that you want an instance variable on the class:

    class Animal
      @noise = "whaargarble"
      class << self
        attr_accessor :noise
      end
      def make_noise
        puts self.class.noise
      end
    end
    
    class Dog < Animal
      @noise = "bark"
    end
    
    a = Animal.new
    d = Dog.new
    a.make_noise  #=> "whaargarble"
    d.make_noise  #=> "bark"
    Dog.noise = "WOOF"
    d.make_noise  #=> "WOOF"
    a.make_noise  #=> "whaargarble"
    

    However, if you are sure that you want a constant:

    class Animal
      def make_noise
        puts self.class::NOISE
        # or self.class.const_get(:NOISE)
      end
    end
    

提交回复
热议问题