In Ruby, is there a way to 'override' a constant in a subclass so that inherited methods use the new constant instead of the old?

后端 未结 3 667
我寻月下人不归
我寻月下人不归 2020-12-10 00:29

In Ruby, is there a way to \'override\' a constant in a subclass in such a way that calling an inherited method from the subclass results in that method using the new consta

3条回答
  •  臣服心动
    2020-12-10 01:06

    I've done this by simply redefining the constant in the subclass, and then referring to it in methods as self.class::CONST in instance methods and self::CONST in class methods. In your example:

    class SuperClass
      CONST = "Hello, world!"
      def self.say_hello
        self::CONST
      end
    end
    
    class SubClass < SuperClass
      CONST = "Hello, Bob!"
    end
    
    SubClass.say_hello #=> "Hello, Bob!"
    

提交回复
热议问题