使用Hash默认值时奇怪的意外行为(消失/更改值),例如Hash.New([])
h = Hash.new(0) # New hash pairs will by default have 0 as valuesh[1] += 1 #=> {1=>1}h[2] += 2 #=> {2=>2}
h = Hash.new([]) # Empty array as default valueh[1] <<= 1 #=> {1=>[1]} ← Okh[2] <<= 2 #=> {1=>[1,2], 2=>[1,2]} ← Why did `1` change?h[3] << 3 #=> {1=>[1,2,3], 2=>[1,2,3]} ← Where is `3`?
{1=>[1], 2=>[2], 3=>[3]}
相关分类