0

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].

3
  • The clue is in the output. See what matrix.each {|a| puts a.object_id } returns. Commented Aug 11, 2016 at 14:17
  • they all are same! got your point Commented Aug 11, 2016 at 14:20
  • matrix = Array.new(5, Array.new(5,9)) (your extra parens are not needed) is the same as arr = Array.new(5,9); matrix = Array.new(5, arr). Got it? Commented Aug 11, 2016 at 17:11

2 Answers 2

7

Basically, you are using the same array reference for every subarray. Do it like this

matrix = Array.new(5) { Array.new(5, 9) }
Sign up to request clarification or add additional context in comments.

1 Comment

ya I have understood what's happening with my declaration. Your declaration worked as charm!
1

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]]

1 Comment

That works but the idiomatic way to create matrix is as given by @ursus.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.