Is this a bug in the Array.fill method in Ruby?

If so, is it I am mistaken, or is it a mistake?

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

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

If this does not lead to:

=> [[nil, nil, nil], ["g", "g", "g"], [nil, nil, nil]]
+5
source share
2 answers

Array.new(3, Array.new(3))returns an array that 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) }one that evaluates Array.new(3)three times and thus gives you an array of three independent arrays.

+9
source

That's right, it Array.new(array)returns a new array created with copies of size obj (that is, size references for the same obj)

0
source

All Articles