Niels Kristian Niels Kristian - 7 months ago 9
Ruby Question

How can I modify positions in a two dimensional array?

If I do the following:

table = Array.new(
3,
Array.new(
3,
nil
)
)

# =>
[
[nil, nil, nil],
[nil, nil, nil],
[nil, nil, nil]
]


Now I would like to modify the value at index 2 in the second array, so I would do:

table[1][2] = 2.343


I would now expect to see:

# =>
[
[nil, nil, nil],
[nil, nil, 2.343],
[nil, nil, nil]
]


However what I'm getting is this:

[
[nil, nil, 2.343],
[nil, nil, 2.343],
[nil, nil, 2.343]
]


What am I not getting here?

PS: Running ruby 2.3

Answer

For fix with behavior, try next:

empty_table = Array.new(3) { Array.new(3) }

From array manual:

Note that the second argument populates the array with references to the same object. Therefore, it is only recommended in cases when you need to instantiate arrays with natively immutable objects such as Symbols, numbers, true or false.