Read more

Ruby / Rails: clone vs. dup vs. deep_dup

Deleted user #4117
May 05, 2020Software engineer

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
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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

Posted to makandra dev (2020-05-05 11:48)