The following are equivalent:
Array.new(5,Array.new(3))
[Array.new(3)] * 5
inside = Array.new(3); [inside, inside, inside, inside, inside]
They will all produce an array containing the same array. I mean the exact same object. That's why if you modify its contents, you will see that new value 5 times.
As you want independent arrays, you want to make sure that the "inside" arrays are not the same object. This can be achieved in different ways, for example:
Array.new(5){ Array.new(3) }
5.times.map { Array.new(3) }
Array.new(5).map { Array.new(3) }
# or dup your array manually:
inside = Array.new(3); [inside.dup, inside.dup, inside.dup, inside.dup, inside]
Note that the Array.new(5, [])
form you used first doesn't copy the obj
for you, it will reuse it. As that's not what you want, you should use the block form Array.new(5){ [] }
which will call the block 5 times, and each time a new array is created.
The Hash
class also has two constructors and is even more tricky.