调用超级超级方法

是否可以在overriden方法中执行类似super.super的操作? 也就是说,绕过直接父母的超级并称为“祖父母”超级?

这不推荐,但你想要的这样的:

 grandparent = self.class.superclass.superclass meth = grandparent.instance_method(:the_method) meth.bind(self).call 

这是通过首先获取祖父类,然后在其上调用instance_method来获得表示祖父母的the_method版本的the_method 。 然后使用UnboundMethod#bindMethod#call在当前对象上调用grandparent的方法。

你可以修改方法的参数,以允许某种可选的’传递给父’参数。 在您孩子的超类中,检查此参数,如果是,请从该方法调用super并返回,否则允许继续执行。

 class Grandparent; def method_name(opts={}); puts "Grandparent called."; end; end class Parent < Grandparent def method_name(opts={}) return super if opts[:grandparent] # do stuff otherwise... puts "Parent called." end end class Child < Parent def method_name(opts={}) super(:grandparent=>true) end end ruby-1.9.2-p0 > Child.new.method_name Grandparent called. => nil 

否则我同意@Femaref,只是b / c有可能并不意味着它是个好主意。 如果您认为有必要,请重新考虑您的设计。

考虑到这是打破OOP(封装)的原则之一,我非常希望它是不可能的。 即使您尝试这样做的情况也会说明您的设计存在问题。