The Ruby docs for dup
say:
In general,
clone
anddup
may have different semantics in descendent classes. Whileclone
is used to duplicate an object, including its internal state,dup
typically uses the class of the descendent object to create the new instance.
But when I do some test I found they are actually the same:
class Test
attr_accessor :x
end
x = Test.new
x.x = 7
y = x.dup
z = x.clone
y.x => 7
z.x => 7
So what are the differences between the two methods?
One difference is with frozen objects. The
clone
of a frozen object is also frozen (whereas adup
of a frozen object isn't).Another difference is with singleton methods. Same story here,
dup
doesn't copy those, butclone
does.Both are nearly identical but clone does one more thing than dup. In clone, the frozen state of the object is also copied. In dup, it’ll always be thawed.
When dealing with ActiveRecord there's a significant difference too:
dup
creates a new object without its id being set, so you can save a new object to the database by hitting.save
clone
creates a new object with the same id, so all the changes made to that new object will overwrite the original record if hitting.save
Subclasses may override these methods to provide different semantics. In
Object
itself, there are two key differences.First,
clone
copies the singleton class, whiledup
does not.Second,
clone
preserves the frozen state, whiledup
does not.The Rubinius implementation for these methods is often my source for answers to these questions, since it is quite clear, and a fairly compliant Ruby implementation.
The newer doc includes a good example: