0
0
Rubyprogramming~5 mins

Object#dup and Object#clone in Ruby

Choose your learning style9 modes available
Introduction

Sometimes you want to make a copy of an object to change it without affecting the original. dup and clone help you do that.

When you want to copy an object but keep the original safe from changes.
When you want to create a similar object with the same data but separate identity.
When you want to copy an object including its special settings or not.
When you want to experiment with an object without changing the original.
Syntax
Ruby
copy = original.dup
copy = original.clone

dup makes a shallow copy without copying the object's frozen state or singleton methods.

clone makes a shallow copy including frozen state and singleton methods.

Examples
Both dup and clone create a new string with the same content.
Ruby
original = "hello"
copy1 = original.dup
copy2 = original.clone
dup copies the object but does not copy singleton methods if any.
Ruby
class MyClass
  def greet
    "hi"
  end
end

obj = MyClass.new
copy = obj.dup
dup does not copy frozen state, but clone does.
Ruby
obj = "hello"
obj.freeze
copy1 = obj.dup
copy2 = obj.clone
puts copy1.frozen?
puts copy2.frozen?
Sample Program

This program shows how dup and clone create copies of an object. Changing the copies does not change the original.

Ruby
class Person
  attr_accessor :name
end

person1 = Person.new
person1.name = "Alice"

person2 = person1.dup
person3 = person1.clone

person2.name = "Bob"
person3.name = "Carol"

puts "person1 name: #{person1.name}"
puts "person2 name: #{person2.name}"
puts "person3 name: #{person3.name}"
OutputSuccess
Important Notes

Both dup and clone make shallow copies. If the object has other objects inside, those are not copied but shared.

clone copies the frozen state and singleton methods, dup does not.

Use dup when you want a simple copy. Use clone when you want an exact copy including special states.

Summary

dup and clone make copies of objects to avoid changing the original.

dup copies the object but skips frozen state and singleton methods.

clone copies everything including frozen state and singleton methods.