a = Array.new(3,[]) => [[], [], []]
a[1].push(3) => [[3],[3],[3]]
Is this correct? a[1].push(3) is the same as a[2].push(3)? If the
constructor creates the same copy for all array elements, shouldn’t the
array create copies when writing?
a = Array.new(3,) => [, , ]
a[1].push(3) => [[3],[3],[3]]
Is this correct? a[1].push(3) is the same as a[2].push(3)? If the
constructor creates the same copy for all array elements, shouldn’t the
array create copies when writing?
I’m not sure I follow the question, but the general thing going on is:
a[0] and a[1] and a[2] are references to the same object, so if you
change the object through one of those references, the change will be
visible in all of them.
Using map! seems the fastest way, thanks for the tip!
– Christian
···
-----Original Message-----
From: George Ogata [mailto:g_ogata@optushome.com.au]
Sent: Thursday, August 15, 2002 4:14 AM
To: ruby-talk ML
Subject: RE: Is this array operation correct?
Then, do something like:
Array.new(3).map { }
Is there something shorter/more efficient?
If you don’t like using Array.new, you can #map to a Range:
(1…3).map{}
(Dunno about efficiency, here.)
If you’re going to map to a fresh Array, though, you may as well use the
in-place version: