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 662
我寻月下人不归
我寻月下人不归 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:04

    If you have the luxury of being able to change the base class, consider wrapping the "constants" that need changing in class methods in the base class and overriding them as needed in subclasses. This removes the potential for confusion between parent and subclass constants. For the example, this would be as follows:

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

提交回复
热议问题