5

Should this be the case i.e. I am misunderstanding, or is it a bug?

a = Array.new(3, Array.new(3))
a[1].fill('g')

=> [["g", "g", "g"], ["g", "g", "g"], ["g", "g", "g"]]

should it not result in:

=> [[nil, nil, nil], ["g", "g", "g"], [nil, nil, nil]]
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Roja Buck
  • 2,354
  • 16
  • 26

2 Answers2

9

Array.new(3, Array.new(3)) returns an array which contains the same array three times (in other words: the expression Array.new(3) is evaluated exactly once and no copies are made).

What you probably want is Array.new(3) { Array.new(3) }, which evaluates Array.new(3) three times and thus gives you an array of three independent arrays.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
0

It is correct, Array.new(array) returns a new array created with size copies of obj (that is, size references to the same obj)

Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373