From: Robert Klemme Date: 2009-02-17T06:55:00+09:00 Subject: Re: Inherit and override in the same time? On 16.02.2009 16:29, Philippe Lang wrote: > Hi Ruby gurus, > > Let's say we have a Parent class, and a Child1 class that inherits from > the Parent class. > > I'd like to create a Child2 class that inherits most of the Child1 > class, except for one method, which I'd like to override completely. The > problem is that I need to call the method in the Parent class, and > apparently "super.super" is not supported: > > ---------------------------- > class Parent > def go > puts 'parent' > end > end > > class Child1 < Parent > def go > super > puts 'child1' > end > def a_method_id_like_to_inherit > end > end > > class Child2 < Child1 > def go > super.super > puts 'child2' > end > end > > Child2.new.go > ---------------------------- > in `go': undefined method `super' for nil:NilClass (NoMethodError) > ---------------------------- > > I ended up doing this, which apprently works. > > ---------------------------- > class Parent > def go > puts 'parent' > end > end > > class Child1 < Parent > def go > super > puts 'child1' > end > def a_method_id_like_to_inherit > end > end > > class Child2 < Child1 > def go > self.class.superclass.superclass.instance_method( :go ).bind( self > ).call > puts 'child2' > end > end > > Child2.new.go > ---------------------------- > parent > child2 > ---------------------------- > > Isn't there anything simpler than that? Or is that kind of pattern > considered as bad design maybe? IMHO the "bug" is in your inheritance design. You probably should rather do class Parent def go puts 'parent' end end class BaseChild < Parent def a_method_id_like_to_inherit puts 'Boo!' end end class Child1 < BaseChild def go super puts 'child1' end end class Child2 < BaseChild def go super puts 'child2' end end Now, if there are no other classes that should derive from Parent you might as well merge BaseChild and Parent. Kind regards robert