On Tue, Sep 28, 2010 at 10:47 AM, Williams Williams
<shaolinog / hotmail.com> wrote:
> ruby-1.9.2-head > a =3D Array.new(3, Array.new(3, 0))
> =A0=3D> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
> ruby-1.9.2-head > a[0][2] =3D 1
> =A0=3D> 1
> ruby-1.9.2-head > a
> =A0=3D> [[0, 0, 1], [0, 0, 1], [0, 0, 1]]
>
> If the values aren't all 0s, a[0][2] behaves correctly. Am I doing
> something wrong? Thanks.

That constructor of Array takes the second argument, and places it
(the same object) in all positions of the array.
So when you modify that object, you see the modification in all
positions. If you want a different object in each position, try the
block form:

irb(main):001:0> a =3D Array.new(3,Array.new(3,0))
=3D> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
irb(main):002:0> a[0].object_id
=3D> -609376368
irb(main):003:0> a[1].object_id
=3D> -609376368
irb(main):004:0> a[2].object_id
=3D> -609376368

# Same object id

irb(main):005:0> a =3D Array.new(3) {Array.new(3,0)}
=3D> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
irb(main):006:0> a[0].object_id
=3D> -609423628
irb(main):007:0> a[1].object_id
=3D> -609423638
irb(main):010:0> a[2].object_id
=3D> -609423678

# different object id

Jesus.