unknown
6/20/2006 8:25:00 AM
When you use Array#new, this does create an array of size '3', but with =
a =
reference to the same object.
From the docs:
--
"new Array.new( anInteger=3D0, anObject=3Dnil ) -> anArray
Returns a new array, optionally with a size and initial value (that is, =
=
anInteger references to the same anObject).
--
You can verify this by doing:
a.each {|r| puts r.object_id}
(All of the object ids are the same, showing they're referencing the sam=
e =
object).
So, you just need to construct your multidimensional array differently. =
=
Maybe...
a =3D Array.new
0.upto(2) {|i| a[i] =3D Array.new(3, 0)}
a[1][1] =3D 1
a.each {|r| puts r.join(', ')}
That should give you your
0, 0, 0
0, 1, 0
0, 0, 0
Of course, there's probably a better way to do it..
On Tue, 20 Jun 2006 00:01:26 -0700, Tim L =
<tim.anti@spam.lund-tvam.demon.co.uk> wrote:
> Can anyone explain why this code:
>
> a =3D Array.new(3,Array.new(3,0))
> a[1][1]=3D1
> a.each {|r| puts r.join(', ')}
>
> generates this output?
>
> 0, 1, 0
> 0, 1, 0
> 0, 1, 0
>
> I was expecting this
>
> 0, 0, 0
> 0, 1, 0
> 0, 0, 0
>
> Something wrong with my understanding of Ruby - or conceivably the set=
=
> up on
> my PC?
>
> Tim L
>
>