From: Matthew Desmarais Date: 2005-11-23T07:56:45+09:00 Subject: Re: what is the ruby way to do this? Ken Kunz wrote: >Konstantin, > >When you have a single attribute associated with a key, is it >acceptable to have it in a one-element array? If so, you could do >something like: > >@attributes = {} >.... >@attributes[a.key] ||= [] >@attributes[a.key] << a > >Or, if you don't mind having empty keys return an empty array instead >of nil, you could do: > >@attributes = Hash.new([]) >.... >@attributes[a.key] << a > >Cheers, >Ken > > Careful with this one. When you do this: Hash.new([]) you set the default valued returned by the hash to an array. The problem is that it will always return the same array. So in the example provided above you will end up with an empty hash for @attributes. What you really want is the default block style: Hash.new{|hash, key| hash[key] = []} This will create a new array for each key. It's an extremely sneaky little problem. Regards, Matthew