-1

Here is my code:

but = Array.new(2, []) # => [[], []]
but[1] << 1
but # => [[1], [1]]

If I create an array using this:

but = [[], []]

then the problem does not occur. However, the quantity of subarrays I need to include into but is not a stable variable, and alternatives I know to Array.new, loops etc., are cumbersome.

Why does this happen? Doesn't but[1] << 1 affect only one specific sub-element?

the Tin Man
  • 155,156
  • 41
  • 207
  • 295
A.V. Arno
  • 493
  • 5
  • 10

1 Answers1

1

Because the first sub-array and the second sub-array in but are an identical array object. Affecting the second sub-array entails that the first sub-array is also affected.

Note that arguments are evaluated prior to the method they are passed to. In Array.new(2, []), the sub-array [] is evaluated to a single array object, then that identical array object is used twice in the newly created array.

sawa
  • 160,959
  • 41
  • 265
  • 366