如何在Ruby中从特定的祖先类调用方法?
比如说,我有这样的等级制度:如何在Ruby中从特定的祖先类调用方法?,ruby,oop,inheritance,Ruby,Oop,Inheritance,比如说,我有这样的等级制度: class A def some_method 'From A' end end class B < A def some_method 'From B' end end class C < B def some_method # what's here to receive 'From A' ? end end c = C.new c.some_method # get 'From A' A类 定
class A
def some_method
'From A'
end
end
class B < A
def some_method
'From B'
end
end
class C < B
def some_method
# what's here to receive 'From A' ?
end
end
c = C.new
c.some_method # get 'From A'
A类
定义某些方法
“来自A”
结束
结束
B类
如果我在C中调用super
,我会收到“来自B”的消息。
我应该如何实现C#some_方法来从C.some_方法中的
获取。
执行此操作的最佳实践是什么?您可以使用“未绑定方法”执行此操作:
class A
def some_method
'From A'
end
end
class B < A
def some_method
'From B'
end
end
class C < B
def some_method
A.instance_method(:some_method).bind(self).call
end
end
c = C.new
c.some_method # get 'From A'
A类
定义某些方法
“来自A”
结束
结束
B类
Ruby能够从对象中解除方法的绑定,然后将其绑定到另一个对象。instance\u方法
用于从类而不是该类的特定实例中获取方法对象。稍后,我们可以将该方法绑定到调用some_method
的C
实例,即self
,以便最终在同一行中立即调用该方法
正如另一位用户所说,如果您正在这样做,您可能应该检查程序的设计以使用组合或其他方法。这可以通过使用从B
分支而来的B2
类来解决,而无需重新定义该方法。所以您是说,有时C
是B
s,有时不是?我倾向于同意@bjhaid的观点,C
听起来不是正确的方法(但我可能错了)。嗯,C
s是B
s,但它们也是A
s。所以这里的作文听起来不错。我的评论到哪里去了你比I:D快1秒