在 Ruby 中,有没有办法“覆盖"子类中的常量,以便继承的方法使用新常量而不是旧常量? [英] In Ruby, is there a way to 'override' a constant in a subclass so that inherited methods use the new constant instead of the old?
问题描述
在 Ruby 中,是否有一种方法可以覆盖"子类中的常量,这样从子类调用继承的方法会导致该方法使用新常量而不是旧常量?例如:
In Ruby, is there a way to 'override' a constant in a subclass in such a way that calling an inherited method from the subclass results in that method using the new constant instead of the old one? For example:
class SuperClass
CONST = "Hello, world!"
def self.say_hello
CONST
end
end
class SubClass < SuperClass
override_const :CONST, "Hello, Bob!"
end
SuperClass.say_hello # => "Hello, world!"
SubClass.say_hello # => "Hello, Bob!"
如果没有,有没有办法做这样的事情呢?
If not, is there perhaps a way to do something like this instead?
class SuperClass
CONST = "Hello, world!"
def self.say_hello
CONST
end
end
SubClass = SuperClass.clone
SubClass.send(:remove_const, :CONST)
SubClass.const_set(:CONST, "Hello, Bob!")
SubClass.say_hello # => "Hello, Bob!"
<小时>
注意:我在 irb 中尝试了我的第二个示例,它似乎可以工作,只是在克隆类后类方法似乎无法访问 CONST:
Note: I tried my second example out in irb, and it seems to work except that class methods can't seem to access CONST after I clone the class:
irb(main):012:0> SubClass.say_hello
NameError: uninitialized constant Class::CONST
from (irb):4:in `say_hello'
from (irb):12
from C:/Ruby193/bin/irb:12:in `<main>'
推荐答案
我通过简单地重新定义子类中的常量,然后在方法中将其引用为 self.class::CONST
在实例方法中, self::CONST
在类方法中.在您的示例中:
I've done this by simply redefining the constant in the subclass, and then referring to it in methods as self.class::CONST
in instance methods and self::CONST
in class methods. In your example:
class SuperClass
CONST = "Hello, world!"
def self.say_hello
self::CONST
end
end
class SubClass < SuperClass
CONST = "Hello, Bob!"
end
SubClass.say_hello #=> "Hello, Bob!"
这篇关于在 Ruby 中,有没有办法“覆盖"子类中的常量,以便继承的方法使用新常量而不是旧常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!