Reputation: 739
I have created a two dimensional array and the whole 2D array is populated with 9 like this.
matrix = Array.new(5,(Array.new(5,9)))
Next I am printing the whole array
puts "#{matrix}" # => [[9, 9, 9, 9, 9], [9, 9, 9, 9, 9], [9, 9, 9, 9, 9], [9, 9, 9, 9, 9], [9, 9, 9, 9, 9]]
Next I am assigning 1
to the [0][0]
position.
matrix[0][0] = 1
Then I am again printing the matrix
puts "#{matrix}" # => [[1, 9, 9, 9, 9], [1, 9, 9, 9, 9], [1, 9, 9, 9, 9], [1, 9, 9, 9, 9], [1, 9, 9, 9, 9]]
So, here is the case! Why every row is being affected by this assignment. Shouldn't it only change the value of [0][0]
position.
I am using ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]
.
Upvotes: 0
Views: 1735
Reputation: 7714
The problem is that you are not creating 5 different arrays:
matrix = Array.new(5,(Array.new(5,9)))
this code is creating a new array which is then used five times. So, when you set the cell of the first array to 0, you actually set them all to 0.
To fix this, you need to create individual array, for example this way:
matrix = []
5.times do
matrix.push(Array.new(5,9))
end
Then the code will work the way you expect:
matrix[0][0] = 5
puts matrix # [[5, 9, 9, 9, 9], [9, 9, 9, 9, 9], [9, 9, 9, 9, 9], [9, 9, 9, 9, 9], [9, 9, 9, 9, 9]]
Upvotes: 1
Reputation: 30056
Basically, you are using the same array reference for every subarray. Do it like this
matrix = Array.new(5) { Array.new(5, 9) }
Upvotes: 7