I have an array in Ruby that consists of 5 empty arrays. I am trying to use the << operator to push a string into the first array, but the result is that the string gets pushed into ALL of the arrays. Please help me understand this.
The expected output is:
# => [["car"], [], [], [], []]
but instead I get:
# => [["car"], ["car"], ["car"], ["car"], ["car"]]
irb dump:
1.9.3-p194 :001 > output = Array.new(5, [])
=> [[], [], [], [], []]
1.9.3-p194 :002 > output.inspect
=> "[[], [], [], [], []]"
1.9.3-p194 :003 > output[0].inspect
=> "[]"
1.9.3-p194 :004 > output[0] << "car"
=> ["car"]
1.9.3-p194 :005 > output.inspect
=> "[[\"car\"], [\"car\"], [\"car\"], [\"car\"], [\"car\"]]"
[]array, which is why you see duplicates.