Copying a matrix

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 }
m2[2][2]=2

p m
p m2

On Sep 27, 3:47 pm, John S. [email protected] wrote:


Posted viahttp://www.ruby-forum.com/.

m2 = m.dup
0.upto(m2.size - 1) { |i| m2[i] = m[i].dup; 0.upto(m2[i].size - 1) { |
j| m2[i][j] = m[i][j] } }
m2[2][2] = 100
p m
p m2

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 2, 3], [4, 5, 6], [7, 8, 100]]

Perhaps

m2 = Marshal.load(Marshal.dump(m))

Adam P. wrote:

Perhaps

m2 = Marshal.load(Marshal.dump(m))

Thank you both. It’s nice to have a one line object copy… I never
imagined it would be so … esoteric O_o…

John S. 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 }

On Tue, Sep 28, 2010 at 7:05 AM, Brian C. [email protected]
wrote:

John S. 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 #=> #<TypeError: can’t dup NilClass>
#=> true true
#=> dup of true #=> #<TypeError: can’t dup TrueClass>
#=> true true
#=> dup of false #=> #<TypeError: can’t dup FalseClass>
#=> true true
#=> dup of 1 #=> #<TypeError: can’t dup Fixnum>
#=> true true
#=> dup of 2.0 #=> #<TypeError: allocator undefined for Float>
#=> true true

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs