Ruby and Rails have several methods for creating a new object that looks like another: clone
, dup
, deep_dup
. When using them you should be aware of their differences so that you can select the method you really need.
clone
- Shallow copy: references to other objects/values are copied (instead of cloning those objects/values)
- Clones the object and all its "special object attributes" like
frozen
,tainted
and modules that the object has been extended with - Ruby 2.6 documentation for clone Show archive.org snapshot
dup
- Shallow copy: references to other objects/values are copied (instead of cloning those objects/values)
- Clones the object, but ignores "special object attributes" like
frozen
,tainted
and modules that the object has been extended with - Ruby 2.6 documentation for dup Show archive.org snapshot
deep_dup
- Provided by ActiveSupport
- "Special object attributes" like
frozen
,tainted
and singleton methods are ignored (likedup
) - Behavior depends on implementation
-
Hash
Show archive.org snapshot
: returns a deep copy, i.e. referenced objects/values will be
deep_dup
ed as well -
Array
Show archive.org snapshot
: returns a new array where each object is
deep_dup
ed - any other
Object
Show archive.org snapshot
: calls
dup
, orself
when frozen. If your object has instance variables that are hashes or arrays, those will not bedeep_dup
ed.
-
Hash
Show archive.org snapshot
: returns a deep copy, i.e. referenced objects/values will be
Note that deep_dup
is not a silver bullet and needs to be implemented properly by the object you call it on.
Further Reading
Posted by Judith Roth to makandra dev (2020-05-05 09:48)