Strange ruby behavior when using Hash.new([])
- by Valentin Vasilyev
Consider this code:
h=Hash.new(0) #new hash pairs will by default have 0 as values
h[1]+=1 # {1=>1}
h[2]+=2 # {2=>2}
that's all fine, but:
h=Hash.new([]) #empty array as default value
h[1]<<=1 #{1=>[1]} - OK
h[2]<<=2 #{1=>[1,2], 2=>[1,2]} # why ??
At this point I expect the hash to be:
{1=>[1], 2=>[2]}
But something goes wrong.
Does anybody know what happens?