Posted 3 months ago. Visible to the public. Repeats.

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

  • 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

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

deep_dup

  • Provided by ActiveSupport
  • "Special object attributes" like frozen, tainted and singleton methods are ignored (like dup)
  • Behavior depends on implementation
    • Hash: returns a deep copy, i.e. referenced objects/values will be deep_duped as well
    • Array: returns a new array where each object is deep_duped
    • any other Object: calls dup, or self when frozen. If your object has instance variables that are hashes or arrays, those will not be deep_duped.

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

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Judith Roth
Last edit:
about 1 month ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Judith Roth to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more