Bird
Raised Fist0
Rubyprogramming~10 mins

Object#dup and Object#clone in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Object#dup and Object#clone
Start with original object
↓
Create shallow copy
↓
#clone copies singleton methods
↓
Return new object copy
The flow shows how calling #dup or #clone on an object creates a shallow copy, with #clone also copying singleton methods.
Execution Sample
Ruby
class MyClass
  def greet; 'hello'; end
end
obj = MyClass.new
copy = obj.dup
copy2 = obj.clone
This code creates an object and makes two copies using #dup and #clone.
Execution Table
StepActionObject StateCopy TypeSingleton Methods Copied
1Create objobj with greet methodN/AN/A
2Call obj.dupobj unchangedShallow copyNo
3Call obj.cloneobj unchangedShallow copyYes (if any)
4Modify copy instance varcopy changedcopy independentN/A
5Modify copy2 singleton methodcopy2 changedcopy independentYes
6EndOriginal and copies existN/AN/A
💡 Execution stops after creating copies and showing differences in singleton method copying.
Variable Tracker
VariableStartAfter dupAfter cloneFinal
objOriginal objectOriginal objectOriginal objectOriginal object
copyN/AShallow copy of objShallow copy of objModified copy instance var
copy2N/AN/AShallow copy of obj with singleton methodsModified copy2 singleton method
Key Moments - 2 Insights
Why does #clone copy singleton methods but #dup does not?
Because #clone is designed to copy the entire object including its singleton methods, while #dup only copies instance variables. See execution_table rows 2 and 3.
Are the copies completely independent from the original?
They are shallow copies, so instance variables are copied but nested objects inside them are shared. See variable_tracker for changes after dup and clone.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is true about the copy created by #clone?
AIt creates a deep copy of nested objects
BIt copies singleton methods from the original object
CIt does not copy instance variables
DIt modifies the original object
💡 Hint
Check the 'Singleton Methods Copied' column at step 3 in execution_table.
At which step does modifying the copy's instance variable happen?
AStep 1
BStep 2
CStep 4
DStep 5
💡 Hint
Look at the 'Action' column describing modifications in execution_table.
If the original object has no singleton methods, what difference will #dup and #clone show?
ANo difference in copying singleton methods
B#clone will fail
C#dup will copy singleton methods anyway
DBoth will create deep copies
💡 Hint
Refer to the 'Singleton Methods Copied' column in execution_table steps 2 and 3.
Concept Snapshot
Object#dup and Object#clone create shallow copies.
#dup copies instance variables only.
#clone copies instance variables and singleton methods.
Neither performs deep copy of nested objects.
Use #clone to preserve singleton methods.
Full Transcript
This visual execution trace shows how Ruby's Object#dup and Object#clone work. Starting with an original object, calling #dup creates a shallow copy copying instance variables but not singleton methods. Calling #clone also copies singleton methods if any exist. The execution table traces each step: creating the original object, calling #dup and #clone, and modifying copies. The variable tracker shows how variables change after each operation. Key moments clarify common confusions about singleton methods and shallow copying. The quiz tests understanding of these differences. The snapshot summarizes the key points for quick reference.

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