Probleme with 2-dimensionnal arrays


#1

I can’t understand why this piece of code doesn’t return the array
expected ?

my_array = Array.new(3, Array(3))

3.times do |i|
3.times do [j|
my_array[i][j] = i + j
end
end

it should return :
[[ 0, 1, 2] [1, 2, 3] [2, 3, 4]]

but it returns :
[[2, 3, 4] [2, 3, 4] [2, 3, 4]]

Is my code wrong ?
If so how could I build the expected array ?

Thank you


#2

It has to do with how you construct your array. Your outer array
contains 3 references to the same inner array.

You need to force each inner array to be a separate object, which can
be done like this:

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


#3

Matthew M. wrote:

It has to do with how you construct your array. Your outer array
contains 3 references to the same inner array.

You need to force each inner array to be a separate object, which can
be done like this:

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

Perfect thank you very much…


#4

On Apr 19, 2006, at 11:03 AM, Erard Sebastien wrote:

I can’t understand why this piece of code doesn’t return the array
expected ?

my_array = Array.new(3, Array(3))

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

[[2, 3, 4] [2, 3, 4] [2, 3, 4]]

Is my code wrong ?

The two argument form of the constructor uses the same object in each
slot. Thus, if you change one, all are modified. The block form I
used above will be called to generate each object, getting you the
desired results.

Hope that helps.

James Edward G. II