From: John Wilger Date: 2007-03-15T17:25:08+09:00 Subject: Re: General Ruby OOP Question - using inheritance or include for shared attributes On Mar 15, 12:11 am, "Trans" wrote: > On Mar 15, 1:35 am, james.d.mast...@gmail.com wrote: > > I have a generic Ruby OOP question. Which is the more "correct" way > > to share methods between two similar classes that do not necessarily > > need to inherit from anything else: inheritance or include (as a mix- > > in)? > > When it comes to Ruby there is a huge consideration here: Do you or > will you ever wish to pass on class level methods? Or more technically > speaking, do you want class singleton methods to be in the inheritance > chain? If so then you have to use a class, since modules don't allow > it (to my eternal dismay). For example: > > class X; def self.x; "x"; end; end > class Y < X; end > Y.x #=> x > > module X; def self.x; "x"; end; end > class Y; include X; end > Y.x #=> error Modules may not allow it directly, but it seems that you can work around it easily enough: module A def self.included( other ) def other.foo puts 'bar' end end end class B include A end class C < B end #> B.foo #=> bar # #> C.foo #=> bar Or am I missing something important here? Really, the choice of whether to use inheritance or module inclusion comes down to the question of whether you are sharing identity or just behavior. For instance, do you want: class WalkingThing def walk puts 'walking' end end class Human < WalkingThing end class Robot < WalkingThing end or: module WalkingThing def walk puts 'walking' end end class Human include WalkingThing end class Robot include WalkingThing end A bit contrived, sure -- but hopefully makes the point. -- Regards, John Wilger http://johnwilger.com