考虑以下代码:h = Hash.new(0) # 新的哈希对默认将具有 0 作为值h[1] += 1 #=> {1=>1}h[2] += 2 #=> {2=>2} 这些都很好,但是:h = Hash.new([]) # 空数组...
考虑以下代码:
h = Hash.new(0) # New hash pairs will by default have 0 as values
h[1] += 1 #=> {1=>1}
h[2] += 2 #=> {2=>2}
这一切都很好,但是:
h = Hash.new([]) # Empty array as default value
h[1] <<= 1 #=> {1=>[1]} ← Ok
h[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]}
但事实并非如此。发生了什么事?我怎样才能获得我期望的行为?