0

Here's the code:

# a = Array.new(3, Array.new(3))
a = [[nil,nil,nil],[nil,nil,nil]]
a[0][0] = 1
a.each {|line| p line}

With the output:

[1, nil, nil]
[nil, nil, nil]

but using the commented line:

[1, nil, nil]
[1, nil, nil]
[1, nil, nil]

So why is that?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
CamelCamelCamel
  • 5,200
  • 8
  • 61
  • 93
  • 2
    A similar thing can happen with hashes: http://stackoverflow.com/questions/2698460/strange-ruby-behavior-when-using-hash-new – Andrew Grimm Oct 09 '11 at 22:25
  • possible duplicate of [Is this a Bug in the Array.fill method in Ruby?](http://stackoverflow.com/questions/3285229/is-this-a-bug-in-the-array-fill-method-in-ruby). I just happened to come across the dupe by accident, and realized that it's similar to this one, so it wasn't an easy duplicate to find. – Andrew Grimm Oct 10 '11 at 06:08

1 Answers1

6

The commented line is assigning three of the same reference to the array, so a change to one array will propagate across the other references to it.

As for the 2 arrays vs 3, that's simply a matter of the first line specifying 3 as its first parameter and only specifying 2 array literals in the second line.

To create the nested arrays without having any shared references:

a = Array.new(3) {Array.new(3)}

When passed a block ({...} or do ... end), Array.new will call the block to obtain the value of each element of the array.

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134