如何在继承类中使用重写常量
给定以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我对 Konstantin Haase 的解决方案有一些疑问。当访问继承类的实例化对象中的常量时,将使用父常量。
我必须明确提及该课程。
干杯
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.
cheers
抱歉,我无法让代码格式仅在“答案”中的“注释”中工作,但这是为了回答阿科斯塔迪诺夫向亨德里克提出的问题“这与他的[康斯坦丁]答案有何不同?”
我猜 Hendrik 试图从他的继承类中的方法访问常量。这取决于它是实例方法还是静态方法。它的行为似乎与您在实例方法中所期望的一样。但也许与您对静态方法的期望不同。即使这不是 Hendrik 的意思,这可能值得注意:
如果您具有与 Konstantin 完全相同的类定义,但您向类 A 添加了一个方法,如下所示:
那么您两次都会得到 A:
但是,如果您在 A 中定义该方法通过引用类:
然后你得到:
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:
Then you get A both times:
However if you define the method in A by referencing the class:
Then you get:
如果有人发现这个并使用模块扩展,只需使用
self::CONST
In case anyone finds this and is using module extension instead, just use
self::CONST