The Difference between Dup and Clone in Ruby

09/24/2021

Contents

In this article, you will learn about the difference between dup and clone in Ruby.

The difference between dup and clone

In Ruby, both dup and clone are methods used to create a shallow copy of an object. However, there are some differences between them.

The dup method creates a shallow copy of the object. This means that it duplicates the object, including its instance variables, but not any objects that are referenced by the original object. For example, if the original object contains an array or hash, the dup method creates a new object that has a reference to the same array or hash as the original object. This can lead to unexpected behavior if you modify the array or hash in one of the objects, as it will be reflected in the other object as well.

On the other hand, the clone method creates a shallow copy of the object, just like dup, but it also copies the frozen state and singleton class of the original object. This means that any modifications made to the cloned object will not affect the original object. Additionally, any singleton methods defined on the original object will also be available on the cloned object.

Here’s an example that demonstrates the difference between dup and clone:

class MyClass
  attr_accessor :name, :data

  def initialize(name, data)
    @name = name
    @data = data
  end
end

original = MyClass.new("original", [1, 2, 3])

dupped = original.dup
dupped.name = "dupped"
dupped.data << 4

puts "Original name: #{original.name}" #=> "original"
puts "Dupped name: #{dupped.name}" #=> "dupped"
puts "Original data: #{original.data}" #=> [1, 2, 3, 4]
puts "Dupped data: #{dupped.data}" #=> [1, 2, 3, 4]

cloned = original.clone
cloned.name = "cloned"
cloned.data << 5

puts "Original name: #{original.name}" #=> "original"
puts "Cloned name: #{cloned.name}" #=> "cloned"
puts "Original data: #{original.data}" #=> [1, 2, 3]
puts "Cloned data: #{cloned.data}" #=> [1, 2, 3, 5]

As you can see, modifying the data array in the dupped object also modifies the data array in the original object. However, modifying the data array in the cloned object does not affect the original object.