From: Austin Ziegler Date: 2003-10-03T22:22:05+09:00 Subject: Re: hash of hashes On Fri, 3 Oct 2003 20:17:50 +0900, Paul Argentoff wrote: > On Friday 03 October 2003 14:48, Emmanuel Touzery wrote: >> not sure i understand your question. does this help you? > Here is my example: > irb(main):008:0> a = Hash.new(Hash.new(Array.new(2,0))) This won't work because you're not doing what you're expecting. What you're saying is that a nil key will return a particular Hash where nil keys return a particular array. This would be like saying: arry = Array.new(2, 0) hash = Hash.new(arry) a = Hash.new(hash) a['foo'] # => hash a['foo']['bar'] # => arry What you want is: a = Hash.new do |h, k| h[k] = Hash.new do |h1, k1| h1[k1] = Array.new(2, 0) end end This only works with 1.8 or bettter. Ruby does not auto-vivify hashes or arrays like Perl. Note further that if you do something like: a = Hash.new { |h, k| h[k] = :val; nil } You will get a perhaps surprising -- but entirely correct -- result: a['foo'] # => nil a['foo'] # => :val When you attempt to access a nonexistant hash key, the default value is returned. In this case, it's nil. However, in the block you have also set a side effect of setting the hash key provided to :val, so the next time you access 'foo', it's no longer nonexistant. -austin -- austin ziegler * austin@halostatue.ca * Toronto, ON, Canada software designer * pragmatic programmer * 2003.10.03 * 09.15.49