From: Colin Bartlett Date: 2010-09-29T00:15:38+09:00 Subject: Re: copying a matrix. --002354867b481fdc5d04915351a4 Content-Type: text/plain; charset=ISO-8859-1 On Tue, Sep 28, 2010 at 7:05 AM, Brian Candler wrote: > John Smith wrote: > > How can I create an array copy that > > does not reference the same object... > > I have tried this without luck. > > m2 = m.map { |e| e } > > Try: > m2 = m.map { |e| e.dup } or maybe use: m = [ "a", nil, true, false, 1, 2.0 ] m2 = m.map { |e| e.dup rescue e } I've wondered in the past why there isn't a dup or clone alternative which for nil, true, false, Integer, Floats (anything else?) just returns the object itself. Is there any easy way of telling whether an object will respond to dup or clone? For all those objects listed above which won't dup or clone obj.respond_to?(:dup) #=> true on my computer If the OP needs more than 2 levels of dups, this may be a case for more general recursion, discussed here http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/360651 prompted by this thread: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/360275 *** ruby 1.9.1p243 (2009-07-16 revision 24175) [i386-mingw32] m = [ "a", nil, true, false, 1, 2.0 ] m2 = m.map { |e| begin e.dup rescue puts "#=> dup of #{e.inspect} #=> #{$!.inspect}" puts "#=> #{e.respond_to?(:dup)} #{e.respond_to?(:clone)}" e end } #=> dup of nil #=> # #=> true true #=> dup of true #=> # #=> true true #=> dup of false #=> # #=> true true #=> dup of 1 #=> # #=> true true #=> dup of 2.0 #=> # #=> true true --002354867b481fdc5d04915351a4--