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

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

    one way to do it without class instance variables:

    class Animal
    
     def make_noise
       print self.class::NOISE
     end
    
    end
    
    class Dog < Animal
      NOISE = "bark"
    end
    
    d = Dog.new
    d.make_noise # prints bark
    

提交回复
热议问题