Clone objects in Ruby: dup vs. clone

August 21, 2022  ‐ 1 min read

When you need to clone an object in Ruby you basically have two options. You can reach for either the #dup or #clone method. The two methods achieve mostly the same results, but they are no aliases of each other like some Ruby methods.

The #clone method copies over the object attributes as well to the new object. While #dup typically uses the object class to initialize a second object.

Thus, when cloning an object the internal state is maintained in the clone. For example whether the object was frozen or not.

s = 'Original'.freeze

puts s.dup.frozen?
#=> false
puts s.clone.frozen?
#=> true