tupini07
tupini07

Reputation: 558

Changing an array

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?

Upvotes: 1

Views: 38

Answers (1)

BroiSatse
BroiSatse

Reputation: 44675

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) { '*' } }

Upvotes: 3

Related Questions