1

I created an array this way:

 arr = Array.new(4, Array.new(4, '*'))

When I try to change one element, for example the first element of the first array:

 arr[0][0] = 3

then every first element is changed.

 print arr
 [[3, "*", "*", "*"], [3, "*", "*", "*"], [3, "*", "*", "*"], [3, "*", "*", "*"]]

Can someone explain why this is happening?

1 Answer 1

3

Do:

arr = Array.new(4) { Array.new(4, '*') }

Ruby array is in fact a set of pointers, which points onto some other objects n the memory. In your code all the pointers point to the same object created with Array.new(4, '*'). if, instead of the value, you will pass a block, this block will be executed for every element of the array, so each pointer will point to a new object in the memory.

In fact, the code above still have a similar issue with a string '*'. You should use same method to fix it:

arr = Array.new(4) { Array.new(4) { '*' } }
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much :) .. I should have thought about the pointers

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.