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”)
emmanuel
PS: don’t think it matters, but i’m running ruby 1.6.7 (2002-03-01)
[i586-mswin32]
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
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:
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.
i expected that myOtherHash would be {“blue”=>{“red”=>1}}
No, there’s no autovivification in the Perl manner
This not quiet true (for 1.8) - see Guy’s post.
The block default value technique is vivification, but it’s not auto That’s the thing: Emmanuel’s expectation was Perl-style, whereas
in Ruby you have to supply the vivification routine yourself.