From: mike@... (Mike Stok) Date: 2003-08-12T22:43:49+09:00 Subject: Re: hash default value In article <3F38FA17.1080008@wanadoo.fr>, Emmanuel Touzery wrote: >Hello, > > I'm bitten by a hash default value problem. I wanted to avoid the >myHash[a] = {} if !myHash[a]; myHash[a]["blue"] = 1 > pattern by using hash default values, but i get an unexpected (for >me) result: > >irb(main):001:0> myHash = {} >{} >irb(main):002:0> myHash["blue"]["red"] = 1 >NameError: undefined method `[]=' for nil > from (irb):2 >irb(main):003:0> myOtherHash = Hash.new({}) >{} >irb(main):004:0> myOtherHash["blue"]["red"] = 1 >1 >irb(main):005:0> p myOtherHash >{} >nil > >i expected that myOtherHash would be {"blue"=>{"red"=>1}} > >what am i missing here? is there a workaround to the ugly syntax i said >i want to avoid? (you have the right to say "store your data in a decent >manner") In recent rubys (I tried on 1.8) you can say myHash = Hash.new { |h, k| h[k] = Hash.new } so that the newly created sub-hash is installed in the original hash. This behaves as you want... >> myHash['blue']['red'] = 1 => 1 >> myHash['blue']['green'] = 2 => 2 >> myHash['crimson']['king'] = 69 => 69 >> p myHash {"crimson"=>{"king"=>69}, "blue"=>{"green"=>2, "red"=>1}} Hope this helps, Mike -- mike@stok.co.uk | The "`Stok' disclaimers" apply. http://www.stok.co.uk/~mike/ | GPG PGP Key 1024D/059913DA mike@exegenix.com | Fingerprint 0570 71CD 6790 7C28 3D60 http://www.exegenix.com/ | 75D2 9EC4 C1C0 0599 13DA