From: Martin DeMello Date: 2006-01-26T23:48:23+09:00 Subject: Re: Hash with array as value type Robert Klemme wrote: > Michael McGreevy wrote: > > Hello all, > > > > I would like to store arrays in a hash, indexed by a string key. I > > would like to have the hash create an empty array as the default > > value, when it sees a new key, something like the code involving > > "hash1" below. However, this code is giving some strange results -- > > it claims that the hash is empty, even though there is an array > > stored in it, and I can then retrieve that array. > > > > I am new to ruby, so maybe I am just doing something stupid (... I am > > not sure about that "Hash.new( [] )" for example... ) > > > > Can anyone explain these results? > > Yes. You ran into the typical Hash pitfal: the default value is the one > returned if something is not found for the given key. But it never > changes the hash and there is just this single instance. Consider this: I find it instructive to think of the default as a #key_missing method, analogous to #method_missing. martin