2010/4/23 Rolf Pedersen said:
The code ar =3D Array.new(n, []) actually makes n copies of the same obje= ct
(empty array), so each time you do either ar[0] << e or ar[1] << e you ar= e
appending elements to the same array.
That description is inconsistent and might confuse one or the other
reader: there are no copies made of the *object* (Array in this case)
but only of the *reference*!
irb(main):001:0> a =3D Array.new(3,[])
=3D> [[], [], []]
irb(main):002:0> a.map {|x| x.object_id}
=3D> [135000124, 135000124, 135000124]
irb(main):003:0> a.map {|x| x.object_id}.uniq
=3D> [135000124]
The idiom you describe when you say "copy" is the block form of Arra.new:
irb(main):004:0> a =3D Array.new(3) { [] }
=3D> [[], [], []]
irb(main):005:0> a.map {|x| x.object_id}
=3D> [135669212, 135669198, 135669184]
irb(main):006:0> a.map {|x| x.object_id}.uniq
=3D> [135669212, 135669198, 135669184]