From: Mike Fletcher Date: 2006-01-26T22:19:53+09:00 Subject: Re: Hash with array as value type 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? > > Thanks. > > CODE: > > #!/usr/bin/ruby > > > hash1 = Hash.new( [] ) This makes a new Hash with the default value being the Array reference you've passed it. This is only executed *once*, so each new key/value pair points to the *same* Array instance. You want hash1 = Hash.new { |h,k| Array.new } That'll make a new Array instance each time it needs a new default value for a new key. -- Posted via http://www.ruby-forum.com/.