From: Len Lawrence Date: 2008-03-22T23:14:52+09:00 Subject: Re: Cloning arrays On Sat, 22 Mar 2008 08:37:46 -0500, Stefano Crocco wrote: > On Saturday 22 March 2008, Len Lawrence wrote: 0 > a = %w[a b c] > b = a.dup > puts "The ID of a is #{a.object_id}" > puts "The ID of b is #{b.object_id}" > puts "a is the same object as b? #{a.equal? b}" > > puts "The ID of the contents of a: #{a.map{|i| i.object_id}.join(', ')}" > puts "The ID of the contents of b: #{b.map{|i| i.object_id}.join(', ')}" > a.each_index do |i| > puts "a[#{i}] is the same object as b[#{i}]? #{a[i].equal? b[i]}" > end > > produces: > The ID of a is -605837488 > The ID of b is -605837528 > a is the same object as b? false > The ID of the contents of a: -605837498, -605837508, -605837518 > The ID of the contents of b: -605837498, -605837508, -605837518 > a[0] is the same object as b[0]? true > a[1] is the same object as b[1]? true > a[2] is the same object as b[2]? true > > This means that while a and b are not the same object (and so, you can modify > one, for example adding or removing an item, leaving the other as is), they > contain the same objects. So, calling 'destructive' methods (that is, methods > which change the receiver) on the elements of one of the array will also > change the corresponding element of the other array (because they contain the > same object). > > To achieve what you want, you need deep copy. As someone on this list > recently pointed out, you can usually achieve this using marshal: > > b = Marshal.load(Marshal.dump(a)) > > The problem is that with rubytk you're dealing with a C extension, and > with objects created in C, which may, or may not, work correctly with > marshal. If you find out they don't, you can try to manually > deep-duplicate the array. In the simple case of my example above, you > can do: > > b = a.map{|i| a.dup} > > If your array is a nested array, things become more complicated, as > you'd need nested loops. You also need to keep in mind that object > created from C extensions may not be clonable. In this case, there's > nothing to do. > > I hope this helps Thanks Stefano; it sure does. I missed the earlier references to Marshalling - not enough time to keep up with the newsgroup. I can cope with nested arrays. Anyhow, many thanks for the education. Len