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

前端 未结 5 819
闹比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

    If you want it the Object-Oriented Way (TM), then I guess you want:

    class Animal
      # abstract animals cannot make a noise
    end
    
    class Dog < Animal
      def make_noise
        print "bark"
      end
    end
    
    class Cat < Animal
      def make_noise
        print "meow"
      end
    end
    
    d = Dog.new
    d.make_noise # prints bark
    
    c = Cat.new
    c.make_noise # prints meow
    

    If you want to refactor to prevent duplicating the code for print:

    class Animal
      def make_noise
        print noise
      end
    end
    
    class Dog < Animal
      def noise
        "bark"
      end
    end
    
    class Cat < Animal
      def noise
        if friendly
          "meow"
        else
          "hiss"
        end
      end
    end
    
    d = Dog.new
    d.make_noise # prints bark
    
    c = Cat.new
    c.make_noise # prints meow or hiss
    

提交回复
热议问题