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?
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
You might need to refer to this
Array.new(3,Array.new(2,0))
can be understood in 2 steps -
a new array Array.new(2,0)
is created
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With