From: Bob Hutchison Date: 2006-05-23T10:40:20+09:00 Subject: Re: initializing instance variables in a module Hi, On May 22, 2006, at 12:20 PM, Tim Hunter wrote: > Jeff Rose wrote: >> but just initializing on inclusion seems to be the most reasonable >> way, doesn't it? >> > > Put the initialization code in the module's initialize method and have > every class that includes the module call super from its initialize > method: > > module Foo > def initialize(*args, &block) > # whatever... > end > end > > class Bar > include Foo > def initialize(*args, &block) > super # calls Foo's initialize > # more stuff > end > end What is wrong with what Tim suggests? I must be missing something. Here is a specific example: module Foo def initialize super @foo_the_stuff = {} end def add_stuff(key, stuff) @foo_the_stuff[key] = stuff end end class Bar include Foo def show_stuff puts "stuff: #{@foo_the_stuff.inspect}" end end b1 = Bar.new b2 = Bar.new b1.add_stuff("one", 1) b2.add_stuff("two", 2) b1.add_stuff("three", 3) b2.add_stuff("four", 4) b1.show_stuff b2.show_stuff Cheers, Bob ---- Bob Hutchison -- blogs at Recursive Design Inc. -- Raconteur -- xampl for Ruby --