Atsushi
Atsushi

Reputation: 361

loop updating the entire column of the 2D array in ruby

I'm running the following code with Ruby version 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-linux]:

table = Array.new(3, Array.new(3, 0))
for i in 1..2
  table[i][0] = i
end
p table

I expect this to print:

[
 [0, 0, 0],
 [1, 0, 0],
 [2, 0, 0]
] 

Instead I'm somehow getting:

[
 [2, 0, 0],
 [2, 0, 0],
 [2, 0, 0]
] 

I can reproduce this with other loops. Any idea what's going on here?

Upvotes: 1

Views: 39

Answers (1)

Stefan
Stefan

Reputation: 114248

Any idea what's going on here?

Your 3 inner arrays are actually all the same object. (See Common gotchas)

To get an array of 3 different arrays, you have to pass a block to Array.new:

table = Array.new(3) { Array.new(3, 0) }

The inner array Array.new(3, 0) doesn't need the block form because 0 is immutable.

Upvotes: 2

Related Questions