0

I have an array of hashes that will likely have similar keys but different values. When populating them, I notice that trying to update one hash updates them all.

test = Array.new(4, {})
test[0][:test] = 1
test
=> [{:test=>1}, {:test=>1}, {:test=>1}, {:test=>1}]

If I manually write out the array, this does not happen.

test = [{}, {}, {}, {}]
test[0][:test] = 1
test
[{:test=>1}, {}, {}, {}]

Can anyone explain why this happening and what the difference is between the two?

Nicholas Hassan
  • 949
  • 2
  • 10
  • 27
  • 1
    Try this: `test = Array.new(4, {}) #=> [{}, {}, {}, {}]; test.map { |h| h.object_id } #=> [1440, 1440, 1440, 1440]` and then this: `test = Array.new(4) { {} } #=> [{}, {}, {}, {}]; test.map { |h| h.object_id } #=> [1460, 1480, 1500, 1520]`. What does that tell you? – Cary Swoveland Feb 22 '21 at 06:02
  • I didn't know it worked like that! It's important to me to create a variable amount of hashes within the array. Right now I'm appending hashes in a loop to an empty array. It works well enough but it feels lazy. Is there a similar shorthand to Array.new that could achieve this? – Nicholas Hassan Feb 22 '21 at 06:14
  • 1
    You could of course write `test = Array.new(n) { {} }`, where `n` is a variable whose value is determined at runtime. – Cary Swoveland Feb 22 '21 at 08:32
  • Thanks! I don't expect you go into full detail, but is there a term or situation that describes when it would be useful to have multiple of the same object? It seems redundant for most scenarios – Nicholas Hassan Feb 22 '21 at 16:06

0 Answers0