Why array of arrays gets corrupted?


#1

What’s wrong with this:

a = Array.new(2, [] of Int32)
a[0] << 1
puts a #=> [[1], [1]]

Both elements of array becomes [1]. Why?


#2

Ok, I got it: only one [] of Uint32 is created and array a holds the same reference to this empty array in both cells.

But how should I properly create an array of arrays then?


#3

a = [] of Array(Int32)


#4
a = Array.new(2) { [] of Int32 }
a[0] << 1
puts a #=> [[1], []]

The block form lets you do this. The block is invoked once per array.size.