From: Tim Hunter Date: 2006-03-12T09:18:44+09:00 Subject: Re: Strange behaviour Javier Valencia wrote: > Look this: > > tigre@enigma tigre $ irb > irb(main):001:0> events = {} > => {} > irb(main):002:0> events.default = [] > => [] > irb(main):003:0> events["trying"] << "hello" > => ["hello"] > irb(main):004:0> events > => {} > irb(main):005:0> events.inspect > => "{}" > irb(main):006:0> events["trying"] > => ["hello"] > irb(main):007:0> quit > tigre@enigma tigre $ > > > why is happening this behaviour? > > The "events.default = []" statement establishes a default object to be returned when you access a key that is not in the hash. The same object is always returned. That is, the same array will be returned every time you access a key that is not in the hash. Further, adding an element to that array by fetching a non-existent key does not add the key to the hash. The 'events["trying"] << "hello"' statement sends [] to the hash, which returns the default array, then adds "hello" to the array. To add a key to the hash you have to use its []= method*. Look at this sequence for example: irb(main):001:0> ary = [] => [] irb(main):002:0> hsh = {} => {} irb(main):003:0> hsh.default = ary => [] irb(main):004:0> hsh[:a] << 1 => [1] irb(main):005:0> hsh => {} irb(main):006:0> ary => [1] irb(main):007:0> hsh[:b] = 1 => 1 irb(main):008:0> hsh => {:b=>1} *Okay, for the picky, there's other ways to add a key to a hash. Work with me here.