Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 134 ยท Object-Oriented Ruby

Copying Objects

Learn how Ruby assignment shares objects, how dup and clone make shallow copies, how they differ, and how to write initialize_copy and deep copies safely.

Assigning a variable in Ruby never copies anything. b = a makes b a second name for the same object, so changing the object through one name is visible through the other. This is the root of a whole family of bugs: you hand an array to a method, the method edits it, and the caller's data changes. To get a separate object you have to ask for a copy explicitly.

Ruby offers dup and clone for that, but both make only a shallow copy: the new object is separate, yet the objects inside it are still shared. This lesson shows exactly what is and is not copied, how dup and clone differ, how to customize copying with initialize_copy, and three ways to get a deep copy. It builds on Equality and Identity and Immutability and freeze.

Assignment shares, it does not copy

Ruby Two names, one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

b << 4 changed a too, because both names point to one array. The method add_item modified the caller's array for the same reason: Ruby passes object references, and mutating methods like << act on the shared object. a.dup produced a genuinely new array, so appending to copy left a alone. Immutable values (Integers, Symbols, nil, true, frozen strings) are never a problem, because nobody can change them.

dup: a fresh object with the same state

dup allocates a new object of the same class and copies its instance variables. Because it is a shallow copy, it copies the references in those variables, not the objects they refer to.

Ruby dup copies the container, not its contents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Replacing copy.name with a new string affects only copy, which feels like a real copy. But copy.songs << "Bonus" modified the one array both playlists share, and mix.songs shows the bonus track too. The last line, copy.name << "!", mutates a string in place; it would have been shared too had copy.name still been the original string, but we had already assigned a new string to it, so only the copy's own string changed and mix.name is still "Mix".

The rule to remember: assigning to an attribute is safe, mutating a shared inner object is not.

dup versus clone

clone is dup plus three extras, which matter when you copy objects that carry state beyond their instance variables:

dup clone
Instance variables copied copied
Frozen state not kept (copy is unfrozen) kept (copy is frozen too)
Singleton methods not copied copied
Extended modules (via extend) not copied copied
Ruby What clone keeps that dup drops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The failure message is undefined method 'hi' for an instance of Object: the singleton method lived only on greeter, and dup leaves it behind. A frozen original gives a frozen clone and an unfrozen dup; clone(freeze: false) lets you drop the frozen state while still keeping singleton methods.

Which should you use? Prefer dup when you want an ordinary, modifiable copy of the data. Use clone when you need an exact twin, including frozen state and singleton behavior (for example when copying a configured object).

Copying built-in collections

Array, Hash, String, Set, Struct and Data all support dup and clone. They are shallow too, so a hash of arrays still shares the arrays:

Ruby Shallow copies of nested collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Adding a key to copy left scores unchanged, since the top-level hash is a new object. Appending to copy[:ana] leaked into scores[:ana] because the array inside was never copied. Mapping dup over the elements copies one level deeper, which is enough when your structure is only two levels deep.

Customizing a copy with initialize_copy

When Ruby makes a copy it allocates the new object, copies the instance variables, and finally calls initialize_copy(original) on the copy. Override it to duplicate the inner objects that must not be shared. (initialize_dup and initialize_clone exist too, and call initialize_copy by default.)

Ruby initialize_copy makes the copy independent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Always call super first so the default copying still happens, then replace the fields that need their own copies. Notice that inside initialize_copy the instance variables are already set, so @songs currently points at the shared array; assigning a duplicate to it detaches the copy. This also works with clone, and the frozen state is applied only after initialize_copy finishes, so you can still assign to fields in it.

Do not override dup or clone themselves. They do bookkeeping (frozen state, the singleton class) that is easy to break. initialize_copy is the supported hook.

Deep copies

A deep copy duplicates the whole object graph. Ruby has no built-in deep_dup, but there are three common approaches.

1. Marshal round trip

Marshal.dump turns an object graph into bytes and Marshal.load rebuilds it, producing brand-new objects all the way down. It also preserves shared references and cycles inside the graph.

Ruby Deep copy with Marshal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The original is untouched, and the two inner references to shared are still one object in the copy, so the structure's shape is kept. But Marshal only handles plain data. Proc, Method, IO objects, and singleton-carrying objects cannot be dumped, and the error is no _dump_data is defined for class Proc. It is also slower than a hand-written copy.

Never call Marshal.load on data that came from outside your program (a file upload, a network client): loading arbitrary Marshal data can run attacker-chosen code. Copying your own objects in memory is safe.

2. A recursive helper

For plain hashes and arrays you can write the deep copy yourself, which is faster, safe and easy to adapt:

Ruby A hand-written deep_dup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Strings are copied because they are mutable; numbers and symbols are returned as-is. Add more in branches for the types you use (for example Set or your own classes, via their own deep_dup).

3. Make the data immutable

The cheapest copy is no copy. If you freeze the data, nobody can change it and sharing it is safe. Data.define values and frozen strings are common examples, and Ractor.make_shareable freezes an entire graph deeply (see Immutability and freeze). A new version is made with with rather than by mutation.

Ruby Sharing safely with immutable data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The attempt to append raises can't modify frozen Array: ["x"], which is exactly the guarantee you want: sharing the array between base and other is safe because nobody can edit it.

Pitfalls to remember

  • Default arguments are shared: def add(list = []) makes a fresh array per call, but a constant like DEFAULTS = [] reused as a default is one shared object. dup it before you mutate.
  • Hash.new([]) shares one default: every missing key returns the same array. Use Hash.new { |h, k| h[k] = [] } instead.
  • Array.new(3, []) also repeats one array three times; use Array.new(3) { [] }.
  • dup of a frozen object is not frozen, which makes dup the standard way to get an editable version of a constant.
  • Copy vs equality: a copy is == to the original but never equal?, see Equality and Identity.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After b = a (where a is an array), what does b << 1 do?

    Assignment copies the reference, not the object. Both names point at the same array.
  2. 2. Which statement about dup and clone is correct?

    clone is dup plus frozen state, singleton methods and extended modules. Both are shallow.
  3. 3. A hash { a: [1] } is copied with dup, then the copy's :a array gets a new element. What happens to the original?

    dup is shallow: both hashes hold the same inner array, so mutating it shows in both.
  4. 4. Where should you put code that gives a copy its own inner arrays?

    initialize_copy is the supported hook called on the new object after its instance variables are copied.
  5. 5. What is a limitation of Marshal.load(Marshal.dump(obj)) as a deep copy?

    Marshal cannot serialize procs, methods, IO objects and the like, so a graph containing them raises TypeError.

Summary

  • Assignment copies a reference; dup and clone make a new object but only a shallow copy.
  • clone also keeps frozen state, singleton methods and extended modules; clone(freeze: false) drops only the frozen state.
  • Mutating a shared inner object affects every copy; reassigning an attribute does not.
  • Override initialize_copy (calling super) so a copy owns its inner collections.
  • Deep copy with a Marshal round trip (own data only), a recursive helper, or avoid copying by freezing and using Data#with.
  • Beware shared defaults: Hash.new([]), Array.new(3, []) and mutable constants.

Next: Design Principles in Ruby