How to use an overridden constant in an inheritanced class

后端 未结 4 944
深忆病人
深忆病人 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 08:00

    class A
      CONST = 'A'
    
      def initialize
        puts self.class::CONST
      end
    end
    
    class B < A
      CONST = 'B'
    end
    
    A.new # => 'A'
    B.new # => 'B'
    

提交回复
热议问题