DEV Community

Discussion on: Hash#new

Collapse
 
hkly profile image
hkly

Also good to remember to be careful if you're trying to set your default value to an array, string, or hash. The default value passed in is just reused and mutated

h = Hash.new([])
=> {}
a.each {|i| h[i] <<= i}
=> [1, 2, 3, 4, 1, 1, 3]
h
=> {1=>[1, 2, 3, 4, 1, 1, 3], 2=>[1, 2, 3, 4, 1, 1, 3], 3=>[1, 2, 3, 4, 1, 1, 3], 4=>[1, 2, 3, 4, 1, 1, 3]}

Note that I had to use <<= to assign the value to the key, if you just do <<, h would still be an empty hash.

If I want the default value to be an array, I usually use the third option and pass a block Hash.new { [] }, which will give me a new array for each key.