From: Gary Wright Date: 2007-12-08T09:14:16+09:00 Subject: Re: Problem with Hash of Arrays On Dec 7, 2007, at 7:00 PM, Jimi Damon wrote: > Bernardo Rufino wrote: >> In addition, to create different Arrays objects use a block... >> >> irb(main):001:0> a = Hash.new{|hash, key| hash[key] = Array.new;} >> => {} >> irb(main):002:0> a[:first] >> => [] >> irb(main):003:0> a[:first] << "test" >> => ["test"] > > Yes, but if you run this example and type "a" you get > > irb(main):003:0> a > => {} > > I'm sorry...but I think this is incorrect... You have defined an array > as being the default type , hence after > you have performed << "test" , a should contain > > => {:first=>["test"]} > > But it does not.. > You've mistyped something. a will indeed be "{:first=>["test"]}" if you run Bernardo's example. You're asking a lot of very common questions for programmers who aren't familiar with the behavior of Ruby's Hash class. The bottom line is that you are not pointing out bugs in Ruby's implementation of Hash, just common misunderstandings. 1) Hash.new(x) returns x when a key isn't found. It will be the same x for *every* key and won't store x in the hash, just return it on a key miss. 2) Hash.new { #code } will run the block on every key miss and return the resulting value but will *not* store the value in the hash. 3) Hash.new { |h,k| h[k] = #code } will evaluate the code, store it in the hash, and return the value on a key miss. Because the value is stored in the hash on the first key miss, the code will not execute on a subsequent lookup on the same key. Gary Wright