如何在不影响超类的情况下覆盖 Ruby 子类中的变量? [英] How do I override a variable in a Ruby subclass without affecting the superclass?
问题描述
假设我有一个带有一些静态"变量的类.我希望该类的子类能够覆盖这些变量而不影响原始类.使用类变量是不可能的,因为它们似乎在子类和超类之间共享:
Let's say I have a class with a few "static" variables. I want to a subclass of that class to be able to override those variables without affecting the original class. This isn't possible using class variables, since those appears to be shared between subclasses and superclasses:
class Foo
@@test = "a"
def speak; puts @@test; end
end
class Bar < Foo
@@test = "b"
end
Bar.new.speak
# b
Foo.new.speak
# b
也不可能使用常量:
class Foo
TEST = "a"
def speak; puts TEST; end
end
class Bar < Foo
TEST = "b"
end
Bar.new.speak
# a
Foo.new.speak
# a
超类中定义的方法会忽略子类中的常量.
Methods defined in the superclass ignores constants in the subclass.
显而易见的解决方法是为需要覆盖"的变量定义方法:
The obvious workaround is to define methods for the variables that needs to be "overridable":
class Foo
def test; "a"; end
end
但这感觉就像一个黑客.我觉得这应该可以使用类变量,而且我可能只是做错了.例如,当我将 Object
子类化时(默认情况下会发生这种情况):
But that feels like a hack. I feel like this should be possible using class variables and that I'm probably just doing it wrong. For example, when I subclass Object
(which is what happens by default):
class Foo < Object
@@bar = 123
end
Object.class_variable_get(:@@bar)
# NameError: uninitialized class variable @@bar in Object
为什么在 Object
上设置 @@bar
不像在我的 Bar <Foo
上面的例子?
Why isn't @@bar
set on Object
like it was in my Bar < Foo
example above?
总结:如何在不影响超类的情况下覆盖子类中的变量?
To summarize: how do I override a variable in a subclass without affecting the superclass?
推荐答案
类常量可以做你想做的,你只需要以不同的方式使用它们:
Class constants does what you want, you just need to use them differently:
class Foo
TEST = "a"
def speak
puts self.class::TEST
end
end
class Bar < Foo
TEST = "b"
end
Bar.new.speak # => a
Foo.new.speak # => b
这篇关于如何在不影响超类的情况下覆盖 Ruby 子类中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!