class A
#define class level attribute called key
class 开发者_高级运维<< self
attr_accessor :key
end
end
class B < A
end
B.key = "foo"
B.key # returns "foo"
A.key # returns nil
.
What is the approach if I want A.key to return "foo" in the above scenario?
The only way I know is to manually declare the class functions. Subclasses will return the parent's value, but you cannot have them return a different value.
class A
def self.key
@@key
end
def self.key=(new_val)
@@key = new_val
end
end
Class methods can't be virtual. C'est la vie. When you have a class, you have no virtual table.
精彩评论