From: dblack@... Date: 2006-05-23T03:53:03+09:00 Subject: Re: initializing instance variables in a module Hi -- On Tue, 23 May 2006, Jeff Rose wrote: > Ryan Leavengood wrote: > >> On 5/22/06, Jeff Rose wrote: >>> Have a module: >>> >>> Module Foo >>> def add_stuff(key, stuff) >>> @foo_the_stuff[key] = stuff >>> end >>> end >>> >>> class Bar >>> include Foo >>> end >>> >>> Is there a standard or correct way to initialize @foo_the_stuff in this >>> example? Should the add_stuff method check whether the variable has >>> been initialized every time, or should this be done by implementing a >>> callback like append_features or included? (That's how I'd want to do >>> it, but it's not clear which or how...) >>> >>> Thanks, >>> Jeff >> >> module Foo >> def add_stuff(key, stuff) >> (@foo_the_stuff ||= {})[key] = stuff >> end >> end >> >> If @foo_the_stuff is null, it will be initialized to an empty hash, >> otherwise the existing value will be used. I consider this use of ||= >> to be a Ruby idiom. >> >> Ryan >> > That's what I was afraid of. In this example case it's no big deal, but in a > module where you are accessing a more complex variable many times it's a real > pain, let alone inefficient. We are working on an event system, so the hash > is a hash of arrays or possibly a hash of hashes. Any of 4 methods could be > called, which would require an initialized value. Having this in every > method is sorta lame... > > handlers = (@event_handlers ||= Hash.new {|k,v| k[v] = []})[key] > > Of course we can pull it out to a method: > > def handlers(key) > @event_handlers ||= Hash.new {|k,v| k[v] = []})[key] > end > > but just initializing on inclusion seems to be the most reasonable way, > doesn't it? Not if it leads to code you strongly dislike :-) It seems OK to wrap it in a method, perhaps like this: def event_handlers @event_handlers ||= Hash.new {|k,v| k[v] = []} end def whatever ... handlers = event_handlers[key] end David -- David A. Black (dblack@wobblini.net) * Ruby Power and Light, LLC (http://www.rubypowerandlight.com) > Ruby and Rails consultancy and training * Author of "Ruby for Rails" from Manning Publications! > http://www.manning.com/black