From: Glenn Date: 2009-01-04T22:05:32+09:00 Subject: Re: Default values of hashes --0-1950079755-1231074394=:46277 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: quoted-printable I actually have a followup question to this one.=0A=0AIt turns out that som= etimes I will need to go more than two levels deep with the hashes. I infe= rred that to go three levels deep, the code would be:=0A=0Ah =3D Hash.new{|= h,k| h[k]=3D Hash.new{|h2,k2| h2[k2]=3D Hash.new{|h3,k3| h3[k3]=3D0}}}=0A= =0AThis works fine. It seems, though, that I might have to go more levels = deep than this. I am trying to look for a way to do this dynamically withi= n a method. In other words, if I need 3 levels, it creates a hash within h= ash object 3 levels deep (like in the line of code above) and if I need 5, = it creates one 5 levels deep. I do not know how to do this (or even if it = is possible). Any suggestions on this one?=0A=0AThanks,=0A=0AGlenn=0A=0A= =0A=0A________________________________=0AFrom: Glenn = =0ATo: ruby-talk ML =0ASent: Saturday, January 3, = 2009 9:29:37 PM=0ASubject: Re: Default values of hashes=0A=0ABoth solutions= are great. I had something else that was sort of working, but these are f= ar more elegant.=0A=0AThanks!=0A=0A=0A=0A________________________________= =0AFrom: "Pe=F1a, Botp" =0ATo: ruby-talk ML =0ASent: Saturday, January 3, 2009 12:03:35 AM=0ASubject:= Re: Default values of hashes=0A=0AFrom: Glenn [mailto:glenn_ritz@yahoo.com= ] =0A# I would be able to add any key to trt_hash and its value =0A# would = have a default of an empty hash, and then I'd be able =0A# to add any eleme= nt I wanted to the nested hash, and its =0A# default would be 0. But this = does not seem to work.=0A# ...I thought if I defined trt_hash like this:=0A= # trt_hash =3D Hash.new( Hash.new(0))=0A=0Athat is near to your objective.= you just have to build the hash since defaults do not, ie use the block fo= rm to store value in hash http://www.ruby-doc.org/core/classes/Hash.src/M00= 2868.html=0A=0Atry eg,=0A=0A> trt_hash =3D Hash.new{|h,k| h[k]=3D Hash.new{= |h2,k2| h2[k2]=3D0} }=0A=3D> {}=0A> trt_hash["a"]=0A=3D> {}=0A> trt_hash=0A= =3D> {"a"=3D>{}}=0A> trt_hash["a"][:x]=0A=3D> 0=0A> trt_hash=0A=3D> {"a"=3D= >{:x=3D>0}}=0A> trt_hash["a"][:x]+=3D100=0A=3D> 100=0A> trt_hash=0A=3D> {"a= "=3D>{:x=3D>100}}=0A> trt_hash["a"][:x]+=3D100=0A=3D> 200=0A> trt_hash=0A= =3D> {"a"=3D>{:x=3D>200}}=0A> trt_hash["a"][:w]+=3D100=0A=3D> 100=0A> trt_h= ash=0A=3D> {"a"=3D>{:w=3D>100, :x=3D>200}}=0A> trt_hash["b"][:w]+=3D100=0A= =3D> 100=0A> trt_hash=0A=3D> {"a"=3D>{:w=3D>100, :x=3D>200}, "b"=3D>{:w=3D>= 100}} --0-1950079755-1231074394=:46277--