Sometimes you want to make a copy of an object to change it without affecting the original. dup and clone help you do that.
Object#dup and Object#clone in 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.
dup and clone create a new string with the same content.original = "hello" copy1 = original.dup copy2 = original.clone
dup copies the object but does not copy singleton methods if any.class MyClass def greet "hi" end end obj = MyClass.new copy = obj.dup
dup does not copy frozen state, but clone does.obj = "hello" obj.freeze copy1 = obj.dup copy2 = obj.clone puts copy1.frozen? puts copy2.frozen?
This program shows how dup and clone create copies of an object. Changing the copies does not change the original.
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}"
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.
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.