Changing a two-dimensional ruby ​​array

if I create this array:

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

he creates:

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

And when I try to change a specific item:

a[0][0] = 3

it changes several values:

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

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

+4
source share
2 answers

You will need to change how you initialize your array ( this is a known issue ):

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

The difference between your version and this version is what Array.new(2,0)happens only once. You create one array with 3 "pointers" to the second array. This can be seen 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
+6
source

You may need to refer to this

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

  • new array created Array.new(2,0)

  • 3 (1) .

, . - .

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

+4

Source: https://habr.com/ru/post/1610607/


All Articles