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
···
--
Posted via http://www.ruby-forum.com/.
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) }
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 }
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 ?
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 Gray II
···
On Apr 19, 2006, at 11:03 AM, Erard Sebastien wrote:
Matthew Moss 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...
···
--
Posted via http://www.ruby-forum.com/\.