Bird
Raised Fist0
Rubyprogramming~15 mins

Object#dup and Object#clone in Ruby - Deep Dive

Choose your learning style10 modes available
Overview - Object#dup and Object#clone
What is it?
In Ruby, Object#dup and Object#clone are methods used to create copies of objects. Both make a new object with the same content as the original, but they differ in what they copy and how they handle special object features. Dup creates a shallow copy without copying the object's internal state like frozen status or singleton methods, while clone copies everything including those special features. These methods help when you want to work with a copy without changing the original object.
Why it matters
Without ways to copy objects, programmers would have to manually recreate objects every time they want a similar one, which is slow and error-prone. Dup and clone let you quickly make copies to experiment or modify without affecting the original. This is crucial in programs where objects change state or when you want to keep original data safe. Without these methods, managing object copies would be confusing and inefficient.
Where it fits
Before learning dup and clone, you should understand what objects and variables are in Ruby, and how assignment works (which copies references, not objects). After mastering these methods, you can explore deeper topics like deep copying, freezing objects, and metaprogramming with singleton methods.
Mental Model
Core Idea
Dup and clone make a new object that looks like the original, but clone copies all the hidden details while dup copies only the visible parts.
Think of it like...
Imagine you have a photocopy machine. Dup is like making a simple photocopy of a document—it copies the text but not the sticky notes or highlights on it. Clone is like making a detailed scan that copies the text plus all the sticky notes and highlights exactly as they are.
Original Object
  │
  ├─ dup ──> Shallow copy (no frozen state, no singleton methods)
  └─ clone ─> Full copy (includes frozen state, singleton methods)

Both create new objects with same content, but clone keeps extra features.
Build-Up - 7 Steps
1
FoundationUnderstanding Object References
🤔
Concept: Variables hold references to objects, not the objects themselves.
In Ruby, when you assign a variable to an object, the variable points to that object. If you assign another variable to the first, both point to the same object. Changing the object through one variable affects the other because they share the same object.
Result
Two variables pointing to the same object share changes.
Knowing that variables are references helps understand why copying objects is needed to avoid unintended changes.
2
FoundationWhat is Shallow Copying?
🤔
Concept: Shallow copying creates a new object but copies references inside it, not nested objects.
When you copy an object shallowly, the new object has the same immediate content, but if that content includes other objects, those are not copied—they are shared. For example, copying an array copies the array structure but not the objects inside it.
Result
New object shares nested objects with original.
Understanding shallow copy clarifies why changes to nested objects affect both copies.
3
IntermediateUsing Object#dup for Shallow Copy
🤔Before reading on: do you think dup copies an object's frozen state? Commit to yes or no.
Concept: Object#dup makes a shallow copy but does not copy frozen state or singleton methods.
Calling dup on an object creates a new object with the same content but the new object is not frozen even if the original was. Also, any special methods defined only on the original object (singleton methods) are not copied to the duplicate.
Result
New object with same content but no frozen state or singleton methods.
Knowing dup skips frozen state and singleton methods helps avoid bugs when copying objects that rely on these features.
4
IntermediateUsing Object#clone for Full Copy
🤔Before reading on: does clone copy singleton methods? Commit to yes or no.
Concept: Object#clone copies the object including frozen state and singleton methods.
Clone creates a new object that is a full copy of the original. If the original was frozen, the clone is also frozen. If the original had singleton methods, the clone has them too. This makes clone a deeper copy than dup in terms of object features.
Result
New object fully identical including frozen state and singleton methods.
Understanding clone copies all features prevents surprises when working with objects that have special behaviors.
5
IntermediateDifferences Between dup and clone
🤔Before reading on: which method copies frozen state and singleton methods? dup or clone? Commit to your answer.
Concept: Dup and clone differ mainly in copying frozen state and singleton methods.
Dup copies only the object's content but not its frozen status or singleton methods. Clone copies everything including frozen status and singleton methods. Both perform shallow copies of nested objects.
Result
Clear understanding of when to use dup or clone based on copying needs.
Knowing the exact differences helps choose the right method for copying objects safely.
6
AdvancedLimitations of Shallow Copying
🤔Before reading on: does dup or clone copy nested objects deeply? Commit to yes or no.
Concept: Both dup and clone perform shallow copies; nested objects are shared, not copied.
If an object contains other objects (like arrays or hashes inside), dup and clone copy only the outer object. The inner objects remain shared between original and copy. This can cause unexpected side effects if nested objects are modified.
Result
Understanding that nested objects are shared after dup or clone.
Knowing shallow copy limits prevents bugs when modifying nested data structures.
7
ExpertSingleton Methods and Copying Surprises
🤔Before reading on: do you think dup copies singleton methods? Commit to yes or no.
Concept: Singleton methods are only copied by clone, not dup, which can cause subtle bugs.
Singleton methods are methods defined only on one object, not its class. When you dup an object, these methods are lost in the copy. Clone preserves them. This difference can cause unexpected behavior if code relies on singleton methods after copying.
Result
Awareness of how singleton methods affect object copying.
Understanding singleton method copying avoids subtle bugs in metaprogramming and dynamic behavior.
Under the Hood
Ruby objects store their data and metadata like frozen state and singleton methods internally. When dup is called, Ruby creates a new object copying the instance variables but resets metadata like frozen state and singleton methods. Clone calls dup internally but then copies the frozen state and singleton methods from the original to the new object. Both methods perform shallow copies, so nested objects are not duplicated but referenced.
Why designed this way?
Ruby separates dup and clone to give programmers control over how much of the object's state to copy. Dup is simpler and faster for common cases where frozen state and singleton methods are not needed. Clone is more complete but slightly slower. This design balances performance and flexibility, allowing different copying needs without complex options.
Original Object
╔════════════════════╗
║ Instance Variables ║
║ Frozen State       ║
║ Singleton Methods  ║
╚════════════════════╝
       │
       ├─ dup ──> Copies Instance Variables only
       │          (Frozen State and Singleton Methods lost)
       └─ clone ─> Copies Instance Variables + Frozen State + Singleton Methods
Myth Busters - 4 Common Misconceptions
Quick: Does dup copy an object's frozen state? Commit to yes or no.
Common Belief:Dup copies everything about an object, including frozen state and singleton methods.
Tap to reveal reality
Reality:Dup copies only the object's instance variables; it does not copy frozen state or singleton methods.
Why it matters:Assuming dup copies frozen state can lead to modifying objects thought to be frozen, causing unexpected bugs.
Quick: Does clone perform a deep copy of nested objects? Commit to yes or no.
Common Belief:Clone creates a deep copy, duplicating nested objects inside the original object.
Tap to reveal reality
Reality:Clone performs a shallow copy; nested objects are shared between original and clone.
Why it matters:Believing clone deep copies can cause bugs when nested objects are modified through one copy affecting the other.
Quick: Does dup copy singleton methods? Commit to yes or no.
Common Belief:Dup copies singleton methods along with the object content.
Tap to reveal reality
Reality:Dup does not copy singleton methods; only clone does.
Why it matters:Relying on dup to copy singleton methods can break dynamic behaviors relying on those methods.
Quick: Is dup always faster than clone? Commit to yes or no.
Common Belief:Dup is always faster than clone because it copies less.
Tap to reveal reality
Reality:While dup is usually faster, the difference is often negligible; performance depends on object complexity.
Why it matters:Assuming dup is always better for performance can lead to premature optimization or wrong method choice.
Expert Zone
1
Singleton methods copied by clone include methods added dynamically to individual objects, which can affect behavior in subtle ways after copying.
2
Frozen state copying by clone means the new object cannot be modified, preserving immutability guarantees, which is critical in thread-safe or functional-style code.
3
Dup and clone do not copy tainted or untrusted flags on objects, which can affect security-sensitive code.
When NOT to use
Dup and clone perform shallow copies and do not duplicate nested objects. For deep copying complex nested structures, use custom deep copy methods or libraries like Marshal or deep_clone. Avoid clone when you want a mutable copy of a frozen object, as clone preserves frozen state.
Production Patterns
In production Ruby code, dup is often used to copy objects before modification to avoid side effects. Clone is used when copying objects with singleton methods or frozen state is necessary, such as in metaprogramming or when duplicating immutable objects. Deep copying is handled separately for complex data structures.
Connections
Deep Copying
Builds-on
Understanding dup and clone's shallow copying nature is essential before learning deep copying techniques that duplicate nested objects fully.
Immutability in Functional Programming
Opposite
Clone's copying of frozen state relates to immutability concepts where objects cannot be changed, a key idea in functional programming.
Version Control Systems
Analogy
Just like version control keeps snapshots of code states, dup and clone create snapshots of object states, helping manage changes safely.
Common Pitfalls
#1Modifying a duplicated object expecting nested objects to be independent.
Wrong approach:original = {a: [1, 2]} copy = original.dup copy[:a] << 3 puts original[:a].inspect # Output: [1, 2, 3]
Correct approach:require 'deep_clone' original = {a: [1, 2]} copy = DeepClone.clone(original) copy[:a] << 3 puts original[:a].inspect # Output: [1, 2]
Root cause:Dup performs shallow copy; nested objects like arrays are shared, so modifying them affects both original and copy.
#2Using dup expecting singleton methods to be copied.
Wrong approach:obj = Object.new def obj.special; 'yes'; end copy = obj.dup copy.special # Error: undefined method 'special'
Correct approach:obj = Object.new def obj.special; 'yes'; end copy = obj.clone copy.special # Output: 'yes'
Root cause:Dup does not copy singleton methods; clone does.
#3Using clone on a frozen object expecting a mutable copy.
Wrong approach:obj = 'hello'.freeze copy = obj.clone copy << '!' # Error: can't modify frozen String
Correct approach:obj = 'hello'.freeze copy = obj.dup copy << '!' # Output: 'hello!'
Root cause:Clone copies frozen state, so the copy remains frozen; dup does not copy frozen state.
Key Takeaways
Object#dup and Object#clone both create copies of objects but differ in what they copy beyond the object's content.
Dup makes a shallow copy without copying frozen state or singleton methods, while clone copies these special features too.
Both methods perform shallow copies, so nested objects inside are shared, not duplicated.
Choosing between dup and clone depends on whether you need to preserve frozen state and singleton methods.
Understanding these differences prevents subtle bugs and helps manage object copies safely in Ruby programs.

Practice

(1/5)
1. What is the main difference between dup and clone in Ruby?
easy
A. clone copies frozen state and singleton methods; dup does not.
B. dup copies frozen state and singleton methods; clone does not.
C. dup creates a deep copy; clone creates a shallow copy.
D. clone only copies instance variables; dup copies the entire object.

Solution

  1. Step 1: Understand what dup copies

    dup creates a shallow copy but does not copy frozen state or singleton methods.
  2. Step 2: Understand what clone copies

    clone copies everything including frozen state and singleton methods.
  3. Final Answer:

    clone copies frozen state and singleton methods; dup does not. -> Option A
  4. Quick Check:

    clone copies all [OK]
Hint: Remember: clone copies everything, dup skips frozen and singleton [OK]
Common Mistakes:
  • Thinking dup copies frozen state
  • Confusing shallow and deep copy
  • Assuming clone skips singleton methods
2. Which of the following is the correct syntax to create a copy of an object obj using dup?
easy
A. copy = obj.dup()
B. copy = dup(obj)
C. copy = obj.clone()
D. copy = obj.copy()

Solution

  1. Step 1: Identify the method call syntax

    In Ruby, dup is called on the object as obj.dup or obj.dup().
  2. Step 2: Check other options

    clone is a different method, dup(obj) and copy() are invalid.
  3. Final Answer:

    copy = obj.dup() -> Option A
  4. Quick Check:

    Use obj.dup() to copy [OK]
Hint: Call dup as a method on the object: obj.dup() [OK]
Common Mistakes:
  • Using clone instead of dup
  • Trying dup(obj) as a function
  • Using non-existent copy() method
3. What will be the output of the following Ruby code?
class MyClass
  def greet
    "Hello"
  end
end

obj = MyClass.new
obj_singleton = obj.clone

def obj_singleton.greet
  "Hi"
end

copy1 = obj.dup
copy2 = obj.clone

puts copy1.greet
puts copy2.greet
medium
A. Error at runtime
B. Hello Hi
C. Hi Hi
D. Hello Hello

Solution

  1. Step 1: Understand singleton method copying

    Singleton methods are copied by clone but not by dup. Here, obj_singleton has a singleton method greet returning "Hi".
  2. Step 2: Check what copy1 and copy2 get

    copy1 = obj.dup does not copy singleton methods, so copy1.greet calls original method returning "Hello".
    copy2 = obj.clone copies singleton methods only from obj, not from obj_singleton. Since obj has no singleton method, copy2.greet returns "Hello".
  3. Final Answer:

    Hello Hello -> Option D
  4. Quick Check:

    dup and clone copy singleton only from original object [OK]
Hint: Singleton methods copy only from original object, not clones [OK]
Common Mistakes:
  • Assuming clone copies singleton methods from clones
  • Thinking dup copies singleton methods
  • Expecting 'Hi' output from copy2
4. Consider this Ruby code snippet:
str = "hello"
str.freeze
copy = str.dup
puts copy.frozen?
What is the output and why? If there is an error, identify and fix it.
medium
A. true
B. false
C. NoMethodError
D. RuntimeError

Solution

  1. Step 1: Understand freezing and dup behavior

    The string str is frozen. When dup is called, it copies the object but does NOT copy the frozen state.
  2. Step 2: Check frozen state of copy

    Since dup skips frozen state, copy.frozen? returns false.
  3. Final Answer:

    false -> Option B
  4. Quick Check:

    dup skips frozen state, so frozen? = false [OK]
Hint: dup skips frozen state, clone keeps it [OK]
Common Mistakes:
  • Expecting copy to be frozen
  • Confusing frozen? method with freeze
  • Assuming dup raises error on frozen objects
5. You have an object obj with singleton methods and it is frozen. You want to create a copy that preserves both the singleton methods and the frozen state. Which method should you use and why?
hard
A. Use obj.dup because it copies singleton methods but not frozen state.
B. Use obj.dup and then manually freeze the copy.
C. Use obj.clone because it copies both singleton methods and frozen state.
D. Use obj.clone and then manually add singleton methods.

Solution

  1. Step 1: Identify method that copies singleton methods and frozen state

    dup skips frozen state and singleton methods, so it is not suitable.
  2. Step 2: Confirm clone behavior

    clone copies both singleton methods and frozen state automatically.
  3. Final Answer:

    Use obj.clone because it copies both singleton methods and frozen state. -> Option C
  4. Quick Check:

    clone copies all including frozen and singleton [OK]
Hint: clone copies frozen state and singleton methods together [OK]
Common Mistakes:
  • Using dup and expecting frozen state copied
  • Manually adding singleton methods after clone
  • Freezing after dup instead of cloning
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard