From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2003-04-05T06:21:35+09:00 Subject: Re: To inherit or to include? That is the question. In article , Robert Klemme wrote: > >"Jim Freeze" schrieb im Newsbeitrag >news:20030404085816.A61099@freeze.org... >> For example: >> >> class AppMaker >> def main; ; end >> end >> class MyApp < AppMaker >> end >> MyApp.new.main >> >> or >> >> module AppMaker >> def main; ; end >> end >> class MyApp >> include AppMaker >> end >> MyApp.new.main >> >> I cannot see that the two behave that differently. >> I'm sure there are some differences. Maybe someone >> can help me enumerate them. > >Currently I can't see why you want to inherit a main function - if it's >what I guess, then main is very application specific and does not lend >itself easily for inheritance at all. > >> Ideally, I would like some set of guidelines to help >> me make a choice between these two. >> >> Right now, it's fuzzy to me which one I should use. > >The simples rule is that you have to use inheritance if you want to reuse >state. Modules can only provide methods. So, if you have a set of >related methods that can be expected to be used in different classes, put >them together in a module. But this isn't quite true. You can create/manipulate instance variables withing a modules's methods: module Foo def set_var(v) @var = v end def get_var @var end end class Bar include Foo attr_accessor :var end b = Bar.new b.set_var(42) puts b.var #-> 42 So, the module Foo was able to introduce some state into the class Bar. Phil