From: 7stud -- Date: 2012-12-28T17:15:16+09:00 Subject: Re: Ruby Koans regarding Hashes. Derrick B. wrote in post #1090445: > > hash = Hash.new([]) > => {} > hash[:foo] > => [] > hash[:foo] << "hello" > => ["hello"] > hash[:foo] > => ["hello"] > hash.inspect > => {} > > The last line "hash.inspect" is what I also find interesting, because if > there are default values, why is it still empty? I then assign a value, > overriding the default value: > 1) You never write Hash.new([]) ...because the same array is the default for all keys, and that is never useful. 2) When you write: hash[:non_existent_key] ... you get a reference to the single default array. Unless you *assign* that value to the key, then that key will still have no value. So you need to write: hash[:non_existent_key] <<= "hello" > hash[:foo] = "bar" > => "bar" > hash.inspect > => "{:foo=>\"bar\"}" > > Now, inspect no longer shows an empty hash. Hmmm... > Yes. In this example you assigned something to the key. > Ruby hashes are an interesting topic and I look forward to your veteran > insight on this topic. > This is what you want: hash = Hash.new {|hash, key| hash[key] = []} hash[:one] << 'hello' hash[:two] << 'goodbye' p hash --output:-- {:one=>["hello"], :two=>["goodbye"]} In this case, the block executes when you access a non-existent key, and the block creates a new array and assigns it to the key *and* returns a reference to the array that is assigned to the key. As a result, all you need to do is append to the array. -- Posted via http://www.ruby-forum.com/.