From: "Jesús Gabriel y Galán" Date: 2010-01-26T03:16:44+09:00 Subject: Re: Nested hash with arrays for default value On Mon, Jan 25, 2010 at 6:48 PM, Glen Holcomb wrote: > I'm trying to find a "nice" way to make a nested hash with an empty array as > the default "leaf" value. > > Basically I'd like to be able to make an assignment as follows: > >    data[2][3][4][5] << 3 > > I can get close but I can't get it right.  The data is going to be coming > straight out of a log so I can't really build the hash ahead of time. > > -- > "Hey brother Christian with your high and mighty errand, Your actions speak > so loud, I can’t hear a word you’re saying." > > -Greg Graffin (Bad Religion) > I've not tested this too much, but what I tried was to setup a proxy object that would insert a hash if the [] method is called on it, or an array if the << method was called: class ProxyDefault def initialize hash, key @hash = hash @key = key end def [](key) @hash[@key] = Hash.new {|hash,key| ProxyDefault.new(hash, key)} @hash[@key][key] end def << value @hash[@key] = [] @hash[@key] << value end end h = Hash.new {|hash,value| ProxyDefault.new(hash, value)} h[1][2][3] << "value" p h p h[1][2][3] /temp$ ruby nested_hash_array.rb {1=>{2=>{3=>["value"]}}} ["value"] Hope this helps, Jesus.