What is wrong (Hash default value)?

why the default value didn’t change at the first example but didn’t change at the second I think the default value shoudn’t have been changed at both examples:


#When the default value is a number

hash1 = Hash.new(0)

hash1[“a”] += 1

p hash1[“b”] #this prints 0


#When the default value is an array

hash2 = Hash.new([ ])

hash2[“a”] <<= 1

p hash2[“b”] #this prints [1]

Hash.new(object) always returns the same object as a default. This is why you get [1] for the key “b” because it’s the same array. For an integer it works differently because you are not modifying the integer but replacing the value. It’s basically hash[“b”] = hash[“b”] + 1.

What you want to do instead, is passing the default in a block: Hash.new { } This will evaluate block everytime a key has no value, so you’ll get a new array everytime.