Ruby / Rails: clone vs. dup vs. deep_dup

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

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 (like dup)
  • Behavior depends on implementation

Note that deep_dup is not a silver bullet and needs to be implemented properly by the object you call it on.

Generally speaking, you should prefer deep_dup over dup, but need to know how the object itself implements it.

Further Reading

Almost 4 years ago