Copying and cloning

suggest change

In Ruby, variables hold references to objects rather than the objects themselves. Assigning a variable (b = a) merely creates another reference pointing to the exact same object in memory. To create an independent copy of an object, Ruby provides two built-in methods: dup and clone.


1. References vs. Copies

When you assign one variable to another, modifying the object through either variable affects both:

original = ["apple", "banana"]
alias_ref = original

alias_ref << "cherry"
puts original.inspect
# Output: ["apple", "banana", "cherry"] - both variables reference the same array

To prevent mutations on one variable from affecting the other, you must duplicate or clone the object.


2. dup vs. clone

Both dup and clone create a shallow copy of the receiver, but they behave differently regarding frozen state and singleton methods.

str = "Ruby"
str.freeze

# 1. Handling frozen status
dup_str = str.dup
puts dup_str.frozen? #=> false (dup ALWAYS creates an unfrozen copy)

clone_str = str.clone
puts clone_str.frozen? #=> true (clone preserves the frozen status by default)

# In Ruby 3.0+, you can explicitly unfreeze with clone:
unfrozen_clone = str.clone(freeze: false)
puts unfrozen_clone.frozen? #=> false

Singleton Methods and the Singleton Class

clone copies singleton methods (methods defined on that specific object instance), whereas dup does not:

obj = Object.new
def obj.greet
  "Hello from singleton method!"
end

cloned = obj.clone
duped  = obj.dup

puts cloned.greet #=> "Hello from singleton method!"
# puts duped.greet #=> NoMethodError: undefined method 'greet' for an instance of Object

Comparison Summary

Feature dup clone
Copies instance variables Yes Yes
Copies frozen state No (always unfrozen) Yes (optional via freeze: false in Ruby 3+)
Copies singleton class / methods No Yes
Internal callback initialize_dup / initialize_copy initialize_clone / initialize_copy

3. Shallow Copy Limitations

Both dup and clone perform shallow copies. Only the outer container or object shell is duplicated; any objects referenced by its instance variables or collection items are shared by reference:

original = [{ name: "Alice", scores: [90, 95] }]
shallow_copy = original.dup

# Modifying an element inside the nested hash affects the original!
shallow_copy[0][:scores] << 100

puts original[0][:scores].inspect
# Output: [90, 95, 100] (Original was modified!)

4. Deep Copying Techniques

When you need an entirely distinct object tree where all nested attributes and objects are also copied, you must perform a deep copy.

Approach A: Serialization via Marshal

For objects containing standard serializable Ruby data structures (Strings, Hashes, Arrays, Numbers, Symbols), serialization is the fastest built-in deep-copy mechanism:

def deep_copy(obj)
  Marshal.load(Marshal.dump(obj))
end

original = { user: { name: "Bob", roles: ["admin", "editor"] } }
copy = deep_copy(original)

copy[:user][:roles] << "viewer"

puts original[:user][:roles].inspect
# Output: ["admin", "editor"] (Original remains untouched)

Note: Marshal cannot dump objects containing Proc / closures, open file handles, anonymous classes, or singleton methods (it raises a TypeError).

Approach B: Recursive Deep Copy

For complex domain objects or when Marshal cannot be used:

class Object
  def deep_dup
    case self
    when Array
      map(&:deep_dup)
    when Hash
      each_with_object({}) { |(k, v), h| h[k.deep_dup] = v.deep_dup }
    else
      respond_to?(:dup) ? dup : self
    end
  end
end

nested = { tags: ["ruby", "performance"], meta: { views: 10 } }
cloned = nested.deep_dup
cloned[:tags] << "programming"

puts nested[:tags].inspect
# Output: ["ruby", "performance"]

5. Customizing Copy Behavior with initialize_copy

When an object is duplicated with dup or clone, Ruby allocates a new instance and automatically invokes the private callback method initialize_copy (or initialize_dup / initialize_clone), passing the source object:

class Document
  attr_accessor :title, :sections

  def initialize(title, sections = [])
    @title = title
    @sections = sections
  end

  private

  # Custom copy hook to deep-copy nested sections
  def initialize_copy(source)
    super # Copies primitive instance variables
    # Deep copy the sections array
    @sections = source.sections.map(&:dup)
  end
end

doc1 = Document.new("Ruby Guide", ["Intro", "Syntax"])
doc2 = doc1.dup

doc2.sections << "Advanced"

puts doc1.sections.inspect #=> ["Intro", "Syntax"]
puts doc2.sections.inspect #=> ["Intro", "Syntax", "Advanced"]

Best Practices

  1. Use dup for Routine Duplication: Prefer dup when you want a mutable, fresh copy of an existing object without inheriting its frozen restriction.
  2. Be Mindful of Nested Objects: If an object contains child objects or arrays, remember that dup and clone do not clone the children unless initialize_copy is customized.
  3. Immutability Alternative: Instead of constantly copying mutable data structures to prevent side effects, consider freezing objects (freeze) or using value objects.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents