From: Glenn Date: 2009-01-04T11:29:37+09:00 Subject: Re: Default values of hashes --0-1333564068-1231036237=:98089 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: quoted-printable Both solutions are great. I had something else that was sort of working, b= ut these are far more elegant.=0A=0AThanks!=0A=0A=0A=0A____________________= ____________=0AFrom: "Pe=F1a, Botp" =0ATo: ruby-tal= k ML =0ASent: Saturday, January 3, 2009 12:03:35 A= M=0ASubject: Re: Default values of hashes=0A=0AFrom: Glenn [mailto:glenn_ri= tz@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 a= dd any element 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 l= ike this:=0A# trt_hash =3D Hash.new( Hash.new(0))=0A=0Athat is near to you= r objective. you just have to build the hash since defaults do not, ie use = the block form to store value in hash http://www.ruby-doc.org/core/classes/= Hash.src/M002868.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_hash=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-1333564068-1231036237=:98089--