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?
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?
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?
a = [] of Array(Int32)
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
.