From: Bob Hutchison Date: 2007-03-15T21:34:36+09:00 Subject: Re: General Ruby OOP Question - using inheritance or include for shared attributes On 15-Mar-07, at 4:25 AM, John Wilger wrote: > 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 module A def self.included(other) super other.extend(ClassMethods) end module ClassMethods def foo puts "bar" end end end Is a little cleaner I think. And you can do all kinds of other weird stuff in the self.included method. Another consideration is that in a single inheritance language like Ruby, inheritance is valuable. I tend to use mixins until I'm forced to use inheritance. In a language like Ruby the 'type hierarchy' isn't all that important (duck typing makes it mostly irrelevant). Cheers, Bob ---- Bob Hutchison -- blogs at Recursive Design Inc. -- xampl for Ruby --