如何在继承类中使用重写常量

Tom*_*Tom 33 ruby inheritance class constants

鉴于此代码:

class A
  CONST = 'A'

  def initialize
    puts CONST
  end
end

class B < A
  CONST = 'B'
end

A.new # => 'A'
B.new # => 'A'
Run Code Online (Sandbox Code Playgroud)

我想B使用这个CONST = 'B'定义,但我不知道如何.有任何想法吗?

问候

汤姆

Kon*_*ase 75

class A
  CONST = 'A'

  def initialize
    puts self.class::CONST
  end
end

class B < A
  CONST = 'B'
end

A.new # => 'A'
B.new # => 'B'
Run Code Online (Sandbox Code Playgroud)

  • 是.常量查找通常在编译时绑定. (3认同)