From: Dave Burt Date: 2005-08-29T14:16:22+09:00 Subject: Re: Hash.new(confusion) transfire@gmail.com wrote: > ... > Please explain how r is empty but r[:b] exists. Thank You. # To summarize: h = Hash.new({}) h[1][2] = 3 h #=> {} h.default #=> {2=>3} So you've added to the default object. It might be helpful to note another wrong way to do this: h = Hash.new { {} } h[1][2] = 3 h #=> {} h.default #=> {} Different, because default now returns a new hash every time. But, to answer the implied question, "what is the code that will do what I intend?" there are a few ways to do this: # Just one level of magic new hashes h = Hash.new {|hash, key| hash[key] = {} } h[1][2] = 3 h #=> {1=>{2=>3}} h[1][2][3] = 4 # Error (calling []= on nil) # Auto-vivifying hash: using proc auto_vivivy_hash = proc {|hash, key| hash[key] = Hash.new &auto_vivivy_hash } h = Hash.new &auto_vivify_hash h[1][2][3] = 4 #=> {1=>{2=>{3=>4}}} # Auto-vivifying hash: using Hash subclass class X < Hash def default(key = nil) self[key] = self.class.new end end h = X.new #=> {} h[1][2][3] = 4 h #=> {1=>{2=>{3=>4}}} Cheers, Dave