How to use an overridden constant in an inheritanced class

后端 未结 4 942
深忆病人
深忆病人 2021-02-02 07:27

given this code:

class A
  CONST = \'A\'

  def initialize
    puts CONST
  end
end

class B < A
  CONST = \'B\'
end

A.new # => \'A\'
B.new # => \'A\'
         


        
4条回答
  •  清酒与你
    2021-02-02 07:46

    I had a few issues with the solution by Konstantin Haase. When accessing the constant in an instantiated object of the inheriting class, the parent constant was used.

    I had to explicitly refer to the class.

    self.class::CONST
    

    cheers

提交回复
热议问题