copying a matrix.

J

John Smith

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
 
R

(r.*n){2}

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


m2 = m.dup
0.upto(m2.size - 1) { |i| m2 = m.dup; 0.upto(m2.size - 1) { |
j| m2[j] = m[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]]
 
J

John Smith

Adam said:
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..
 
B

Brian Candler

John said:
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 }
 
C

Colin Bartlett

[Note: parts of this message were removed to make it a legal post.]

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,825
Members
47,371
Latest member
Brkaa

Latest Threads

Top