1
matrix = Array.new(2, Array.new(2, 0))
=> [[0, 0], [0, 0]]

matrix[0][0] = 5
=> 5

matrix
=> [[5, 0], [5, 0]]

Why does it happen? While modifing the assignment I get the following result:

matrix = [[0, 0], [0, 0]]
=> [[0, 0], [0, 0]]

matrix[0][0] = 5
=> 5

matrix
=> [[5, 0], [0, 0]]

1 Answer 1

3

In the first example, you are passing an array object [2, 0] in the second argument of Array.new. The main array will be filled with that same array in two positions. If you modify one of them, the same array in the other position will also be modified.

In the second example, each sub array is a different array. Modifying one of them does not modify the other.

Sign up to request clarification or add additional context in comments.

1 Comment

@antox To correct your code, pass your second argument as block: matrix = Array.new(2) { Array.new(2, 0) }

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.