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].
matrix.each {|a| puts a.object_id }returns.matrix = Array.new(5, Array.new(5,9))(your extra parens are not needed) is the same asarr = Array.new(5,9); matrix = Array.new(5, arr). Got it?