我正在寻找一种方法使一个方法“个人化”--注意不是一个类的私有
这里有一个例子--“个人”,我指的是方法"foo“的行为。
class A
def foo
"foo"
end
end
class B < A
def foo
"bar"
end
end
class C < B
end
a=A.new; b=B.new;c=C.new我正在寻找一种产生以下行为的方法
a.foo #=> "foo"
b.foo #=> "bar"
c.foo #=> "foo" (ultimate base class method called)发布于 2010-04-01 04:44:00
与其创建“个人”方法,不如改变你的继承结构。
您似乎希望C类只具有B类的一些相同功能,而不对A类进行更改。
class A
def foo
"foo"
end
end
class BnC < A
end
class B < BnC
def foo
"bar"
end
end
class C < BnC
end
a=A.new; b=B.new;c=C.new发布于 2010-04-01 04:17:08
没有标准的方法可以做到这一点。它绕过了继承的工作方式。您可以实现B的方法来执行如下逻辑:
def foo
instance_of?(B) ? "bar" : super
end当然,您可以在类上定义一个类似于public和private的方法来为您完成此任务。
class Class
def personal(*syms)
special_class = self
syms.each do |sym|
orig = instance_method(sym)
define_method(sym) {|*args| instance_of?(special_class) ? orig.bind(self).call(*args) : super}
end
end
end然后,您可以像private :foo一样在B中使用personal :foo。
(这根本不是优化的,我没有实现public和private的零参数行为,因为坦率地说,这是一个巨大的PITA,需要正确地做,即使这样,它也是一个技巧。)
发布于 2010-04-01 04:55:07
这看起来可能会令人困惑,但这里有一个选择:
class A
def foo
"foo"
end
end
class B < A
def initialize #when constructing, add the new foo method to each instance
def self.foo
"bar"
end
end
end
class C < B
def initialize #when constructing, do nothing
end
end更广泛地说,使用类似的方法,您总是可以向给定的实例添加方法,这当然不会影响继承的类,甚至不会影响同一类的其他实例。
如果你告诉我们你最终想要实现的目标,我们可能会更有帮助。
https://stackoverflow.com/questions/2556118
复制相似问题