[newbie] What is the difference between dup and clone ?

  • Thread starter Alexey Verkhovsky
  • Start date
A

Alexey Verkhovsky

OK, clone copies frozen state, and dup doesn't (but both copy tainted) -
this much I understand.

But the Rdoc (quoted fully below) hints at some other distinction, saying:

"While clone is used to duplicate an object, including its internal
state, dup typically uses the class of the descendent object to create
the new instance."

In Object, both do a shallow copy. Other standard classes that redefine
this are Set and Matrix - the former redefines dup (to copy the internal
hash table), while the latter redefines clone (which apparently clones
rows - but not cell values).

Maybe it's just my lousy English, but I've got the highest possible
score for reading in IELTS - so supposedly it is not all that lousy, for
a non-native reader.

Whatever it is, I have to humbly ask the collective wisdom of the list
for some enlightenment again.

Best regards,
Alexey Verkhovsky



QTE RDoc

obj.clone -> an_object
Produces a shallow copy of obj—the instance variables of obj are copied,
but not the objects they reference. Copies the frozen and tainted state
of obj. See also the discussion under Object#dup.

obj.dup -> an_object
Produces a shallow copy of obj—the instance variables of obj are copied,
but not the objects they reference. dup copies the tainted state of obj.
See also the discussion under Object#clone. In general, clone and dup
may have different semantics in descendent classes. While clone is used
to duplicate an object, including its internal state, dup typically uses
the class of the descendent object to create the new instance.

UNQTE
 
G

George Ogata

Alexey Verkhovsky said:
OK, clone copies frozen state, and dup doesn't (but both copy tainted) -
this much I understand.

But the Rdoc (quoted fully below) hints at some other distinction, saying:

"While clone is used to duplicate an object, including its internal
state, dup typically uses the class of the descendent object to create
the new instance."

Well, one distinction is that singleton class stuff is `clone'd, but
not `dup'ed:

o = Object.new
class << o
def scare
puts 'boo!'
end
end

o.clone.scare # ok
o.dup.scare # NoMethodError

HTH
 

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,780
Messages
2,569,611
Members
45,273
Latest member
DamonShoem

Latest Threads

Top