Posted 28 days 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

  • deep copy: referenced objects/values will be duped as well
  • "special object attributes" like frozen, tainted and singleton methods are ignored (exactly like dup)
  • Rails 5.2 documentation for deep_dup
  • For most cases this is the preferred method (e.g. when you want to have a duplicate of a hash) (at least when you're working on a Rails project)

Further Reading

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Judith Roth
Last edit:
22 days ago
by Dominik Schöler
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 cookies to improve usability and analyze traffic.
Accept or learn more