From: Jeff Rose Date: 2006-05-23T01:15:11+09:00 Subject: Re: initializing instance variables in a module 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? -Jeff Ryan Leavengood wrote: > 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 > > 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 > >