I have the following code,where I have a hash whose entries are
initalized by an empty Array:
h = Hash.new(Array.new(0))
h = Hash.new { |hash, key| hash[key] = Array.new }
h[“a”] << 0
h[“b”] << 6
h[“a”] << 5
h[“b”] << 10
p h[“a”]
p h[“b”]
Both “p” prints the same: [0,6,5,10]
What am I doing wrong? (I want h[“a”] to be [0,5] and h[“b”]=[6,10]
If you just pass an object to Hash.new() the exact same object is used
to initialize all entries. That’s okay with something like a Fixnum
which will have to be replaced, but not intended with a mutable object
like Array. Switching to the block form as I did above forces Ruby to
run the code each time, getting us a new Array.
Both “p” prints the same: [0,6,5,10]
What am I doing wrong? (I want h[“a”] to be [0,5] and h[“b”]=[6,10]
That form of Hash.new does not create a different new Array for each
new hash key, it creates a single Array instance to which all new hash
keys refer. You might prefer the block form of Hash.new.