From: dblack@... Date: 2003-08-12T22:37:24+09:00 Subject: Re: hash default value Hi -- On Tue, 12 Aug 2003, 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}} No, there's no autovivification in the Perl manner :-) > > 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") The most common technique for this is: my_hash = {} my_hash["blue"] ||= {} # init to hash if not init'd my_hash["blue"]["red"] = 1 which can be trimmed down to: my_hash = {} (my_hash["blue"] ||= {})["red"] = 1 David -- David Alan Black home: dblack@superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav