From: Glen Holcomb Date: 2010-01-26T04:24:53+09:00 Subject: Re: Nested hash with arrays for default value --00032555a39a742a5b047e021f38 Content-Type: text/plain; charset=windows-1252 Content-Transfer-Encoding: quoted-printable 2010/1/25 Jes=FAs Gabriel y Gal=E1n > 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 arr= ay > 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 comi= ng > > 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=92t hear a word you=92re 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 =3D hash > @key =3D key > end > > def [](key) > @hash[@key] =3D Hash.new {|hash,key| ProxyDefault.new(hash= , > key)} > @hash[@key][key] > end > > def << value > @hash[@key] =3D [] > @hash[@key] << value > end > end > > h =3D 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=3D>{2=3D>{3=3D>["value"]}}} > ["value"] > > Hope this helps, > > Jesus. > > Thanks Jesus, I'll play around with your solution. I have the following: data =3D Hash.new { |l, k| l[k] =3D Hash.new { |l, k| l[k] =3D Hash.new { |= l, k| l[k] =3D Hash.new([]) }}} Believe me I know it's ugly and not in any way flexible. Plus it behaves i= n ways which make me uncomfortable when I try to print the contents. --=20 "Hey brother Christian with your high and mighty errand, Your actions speak so loud, I can=92t hear a word you=92re saying." -Greg Graffin (Bad Religion) --00032555a39a742a5b047e021f38--