From: Tom Reilly Date: 2011-04-13T10:52:40+09:00 Subject: Re: hash of arrays Define hash of hashes this way #Using a default hash. foo = Hash.new { |hash, key| hash[key] = Hash.new } foo["a"][1] = "one" foo["a"][2] = "a two" foo["b"][3] = "b three" foo["a"][4] = "b four" p foo["a"][1] p foo["a"][4] p foo["a"].size foo["a"].each {|x,y| p "#{x} #{y}"} David Sprague wrote: > I'm wrote this code to bin a list of words by word-length: > > dict = Hash.new([]) > > dict_file.each do |line| > line.chomp!() > dict[line.length]<< line > end > > expecting that I could avoid testing each time whether this was a new > entry in the hash or not by just appending to the default, an empty > array, > if it is new. > > What happens is that the *same* array is assigned as the default value > to all new entries so that all the hash entries finish with the same > array of values. > > is there away to void having to write something like: > > if dict.key?(line.length) > dict[line.length]<< line > else > dict[line.length] = line > end > > or the ternary equivalent in the inner loop? > > thanks, > > Dave > >