Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modifying two dimensional array ruby [duplicate]

Tags:

ruby

if I create this Array:

a = Array.new(3,Array.new(2,0))

it creates:

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

And when I try to change specific element:

a[0][0] = 3

it changes multiple values:

 => [[3, 0], [3, 0], [3, 0]]

Why is this happening? And how can I change a specific element?

like image 924
Oded Harth Avatar asked Dec 25 '22 13:12

Oded Harth


2 Answers

You'll have to change how you're initializing your Array (this is a known issue) to this:

a = Array.new(3) { Array.new(2,0) }

The difference between your version and this version is that the Array.new(2,0) only occurs once. You're creating one array with 3 "pointers" to the second array. You can see this demonstrated in the following code:

a = Array.new(3,Array.new(2,0))
a.map { |a| a.object_id }
#=> [70246027840960, 70246027840960, 70246027840960] # Same object ids!

a = Array.new(3) { Array.new(2,0) }
a.map { |a| a.object_id }
#=> [70246028007600, 70246028007580, 70246028007560] # Different object ids
like image 161
Gavin Miller Avatar answered Dec 27 '22 03:12

Gavin Miller


You might need to refer to this

Array.new(3,Array.new(2,0)) can be understood in 2 steps -

  1. a new array Array.new(2,0) is created

  2. again a new array is created with 3 elements with the same object (1) in all 3 places.

Hence, changing a value in any of the subarrays changes values in each one of them. The sub arrays are referring to the same object.

As Gavin Miller pointed out, you will need to use a = Array.new(3) { Array.new(2,0) } to change each element.

like image 34
Harish Ved Avatar answered Dec 27 '22 02:12

Harish Ved