0

If I initialize an array of hashes and then assign to 1 element in the array, why are all elements effectively assigned to?

e = Array.new(4, {})
e[0][:test] = 5
e

Now e looks like this, why?:

[{:test=>5}, {:test=>5}, {:test=>5}, {:test=>5}]
  • 2
    See [common gotchas](https://ruby-doc.org/core-2.7.0/Array.html#method-c-new-label-Common+gotchas) in the docs. It almost shows your example. – Stefan Apr 08 '20 at 17:32
  • Hint: `e.map(&:object_id)` – tadman Apr 08 '20 at 17:39
  • Thanks, really appreciate the prompt responses! Interesting behavior - I can only think of limited utility for this. In most scenarios having separate objects is desired, having to use the block syntax to achieve this common requirement is a tad unfortunate. – Ricardo Duncan Apr 08 '20 at 19:38

0 Answers0