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

发布于 2024-09-08 00:05:50 字数 274 浏览 5 评论 0原文

给定以下代码:

class A
  CONST = 'A'

  def initialize
    puts CONST
  end
end

class B < A
  CONST = 'B'
end

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

我希望 B 使用 CONST = 'B' 定义,但我不知道如何操作。有什么想法吗?

问候

汤姆

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'

I'd like B to use the CONST = 'B' definition, but I don't know how. Any ideas?

Greetings

Tom

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

旧人九事 2024-09-15 00:05:50
class A
  CONST = 'A'

  def initialize
    puts self.class::CONST
  end
end

class B < A
  CONST = 'B'
end

A.new # => 'A'
B.new # => 'B'
class A
  CONST = 'A'

  def initialize
    puts self.class::CONST
  end
end

class B < A
  CONST = 'B'
end

A.new # => 'A'
B.new # => 'B'
·深蓝 2024-09-15 00:05:50

我对 Konstantin Haase 的解决方案有一些疑问。当访问继承类的实例化对象中的常量时,将使用父常量。

我必须明确提及该课程。

self.class::CONST

干杯

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

转角预定愛 2024-09-15 00:05:50

抱歉,我无法让代码格式仅在“答案”中的“注释”中工作,但这是为了回答阿科斯塔迪诺夫向亨德里克提出的问题“这与他的[康斯坦丁]答案有何不同?”

我猜 Hendrik 试图从他的继承类中的方法访问常量。这取决于它是实例方法还是静态方法。它的行为似乎与您在实例方法中所期望的一样。但也许与您对静态方法的期望不同。即使这不是 Hendrik 的意思,这可能值得注意:

如果您具有与 Konstantin 完全相同的类定义,但您向类 A 添加了一个方法,如下所示:

def self.print_const
  puts CONST
end

那么您两次都会得到 A:

A.print_const # prints A
B.print_const # prints A

但是,如果您在 A 中定义该方法通过引用类:

def self.print_const
  puts self::CONST
end

然后你得到:

A.print_const # prints A
B.print_const # prints B

Sorry I couldn't get the code formatting to work in a 'comment' only in an 'answer' but this is in response to akostadinov's question to Hendrik "how is this different from his [Konstantin's] answer?"

I'd guess Hendrik was trying to access the constant from methods in his inheriting class & that depends on if it's an instance or static method. It seems to behave as you'd expect in an instance method. But maybe or maybe not how you'd expect for a static method. Even if that's not what Hendrik meant, this may be worth noting:

If you have the exact class definitions as Konstantin, but you add a method to class A like this:

def self.print_const
  puts CONST
end

Then you get A both times:

A.print_const # prints A
B.print_const # prints A

However if you define the method in A by referencing the class:

def self.print_const
  puts self::CONST
end

Then you get:

A.print_const # prints A
B.print_const # prints B
国粹 2024-09-15 00:05:50

如果有人发现这个并使用模块扩展,只需使用

self::CONST

In case anyone finds this and is using module extension instead, just use

self::CONST

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文