0
0
Rubyprogramming~20 mins

Object#dup and Object#clone in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Object Copy Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Difference in frozen state after dup and clone
What is the output of the following Ruby code?
Ruby
str = "hello"
frozen_str = str.freeze
copy_dup = frozen_str.dup
copy_clone = frozen_str.clone
puts copy_dup.frozen?
puts copy_clone.frozen?
A
true
false
B
false
true
C
true
true
D
false
false
Attempts:
2 left
💡 Hint
Remember that dup does not copy the frozen state, but clone does.
Predict Output
intermediate
2:00remaining
Effect of modifying singleton methods after dup and clone
What will be the output of this Ruby code?
Ruby
obj = Object.new
def obj.greet; "hello"; end
obj_dup = obj.dup
obj_clone = obj.clone
puts obj_dup.respond_to?(:greet)
puts obj_clone.respond_to?(:greet)
A
true
true
B
false
false
C
false
true
D
true
false
Attempts:
2 left
💡 Hint
Singleton methods are copied by clone but not by dup.
🔧 Debug
advanced
3:00remaining
Why does modifying a duped object affect the original?
Consider this Ruby code snippet. Why does modifying the duped object also change the original object?
Ruby
class Person
  attr_accessor :name, :address
end

person1 = Person.new
person1.name = "Alice"
person1.address = { city: "NY" }
person2 = person1.dup
person2.address[:city] = "LA"
puts person1.address[:city]
ABecause dup creates a shallow copy, so nested objects like the address hash are shared.
BBecause dup creates a deep copy, so changes to person2 do not affect person1.
CBecause the address hash is frozen and cannot be changed.
DBecause the name attribute is not copied by dup.
Attempts:
2 left
💡 Hint
Think about how dup copies nested objects.
📝 Syntax
advanced
2:00remaining
Which code raises an error when cloning a frozen object?
Which of the following Ruby code snippets will raise a RuntimeError when cloning a frozen object?
A
obj = Object.new.freeze
obj.clone
B
obj = "text".freeze
obj.dup
C
obj = "text".freeze
obj.clone
D
obj = Object.new.freeze
obj.dup
Attempts:
2 left
💡 Hint
Cloning a frozen object of some classes raises an error, but dup usually does not.
🚀 Application
expert
3:00remaining
How to create a deep copy of an object with nested mutable state?
Given a Ruby object with nested mutable objects, which approach correctly creates a deep copy so that modifying nested objects in the copy does not affect the original?
AUse obj.clone to copy the object and its nested objects.
BUse obj.dup to copy the object and its nested objects.
CUse obj.freeze before duplicating to prevent changes.
DUse Marshal.load(Marshal.dump(obj)) to serialize and deserialize the object.
Attempts:
2 left
💡 Hint
Think about how to copy nested objects deeply in Ruby.