“Shannon Fang” xrfang@hotmail.com wrote in message
Surprised, eh ?
I’m indeed surprised by this piculiar behavior. I used the solution you
suggested, it worked fine. tks. But I don’t understand why?
The way I see it is by understanding that if you make the second argument
of Array.new to be another array
(like Array.new(3,Array.new)), only one instance of the Array is created
and its ** reference ** is copied across all the elements.
So, just as
Array(3,0) will create [0,0,0]
Array(3, Array.new) will create [,,]
But all the three arrays in this case ^^^^^
will be refering to only ONE instance (object).
Hence changing any one of them will change all three !
The same logic applies when you do Array.new(3, Array(3, Array.new))
If you study the second solution carefully, you will see that it forces you
to create distinct objects every time. No messing with the references. Hence
you can change any one object without affecting the others.
And as pointed to by David, this can be all done in the single line
a = (1…3).collect { [0,0,0]}
p a # will give [[0,0,0],[0,0,0],[0,0,0]]
HTH,
– shanko