Deep Clone of array?

K

Ken Bloom

Is there a standard way of doing a deep copy of an object (in
particular, of an array)?

http://www.ruby-doc.org/core/classes/Object.html#M000379 mentions a
function 'dclone',
but this doesn't seem to exist:

undefined method `dclone'

It's annoying -- the ruby-doc core documentation includes all of the
standard library, so it's hard to tell what comes from where. (Perhaps
they can regenerate the documentation?)

Anyway, if you click on the function name, you'll see the source code:

# File lib/rexml/xpath_parser.rb, line 8
def dclone
clone
end
 
C

Chris Hayes

Marshal.load(Marshal.dump(array))

I'm curious, has anybody done any benchmarking of this method?

It seems to me this method would have the same kind of overhead &
performance hit as PHP's unserialize(serialize(object)).

I had a similar issue with deep copying an array just now...

Instead of using Marshal, I just extended Array with a roll-my-own:

class Array
def dclone
a = []
each { | x | a << x.dclone }
a
end
end

I think this is a much more robust solution, as it avoids added overhead
that may be hiding inside dump/load, and allows for the deep clone to
further use the children's deep clone methods.

I *believe* this is what the developers intended, as dclone begins as
simply an alias for clone (for basic objects, there's no need to go
deeper. Clone something with no children, and dclone *will* behave
exactly like clone).

This is of course only valid where dclone is defined (likely depends on
the version of ruby you're using). You can modify the above code to be
something more like this:

class Array
def dclone
a = []
each do | x |
if x.respond_to? :dclone
a << x.dclone
else
a << x.clone
end
end
end
end

I'm avoiding my usual habit of using the ? : trinary operator, for
clarity, here.
 

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
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top