rubyguides

String#clone

str.clone -> string

String#clone creates a shallow copy of a string. It is functionally identical to String#dup with one important distinction: clone preserves the frozen status of the original string.

Syntax

str.clone

clone accepts no parameters. It returns a new string object.

Basic Usage

original = "hello world"
copy = original.clone

original << "!"
puts original   # => "hello world!"
puts copy       # => "hello world"

Both clone and dup create shallow copies, so modifying the original does not affect the copy.

Preserving Frozen Status

The key difference between clone and dup is that clone preserves whether the string is frozen:

frozen = "immutable".freeze

clone_copy = frozen.clone
dup_copy = frozen.dup

puts frozen.frozen?        # => true
puts clone_copy.frozen?   # => true
puts dup_copy.frozen?     # => false

If you clone a frozen string, the copy is also frozen. If you dup a frozen string, the copy is thawed and can be modified.

This matters when working with frozen string literals or when you explicitly freeze strings for performance or immutability:

# Frozen string literal (Ruby 3.0+)
frozen_literal = "already frozen".freeze

puts frozen_literal.clone.frozen?   # => true

Shallow Copy Behavior

Like dup, clone creates a shallow copy. The string’s instance variables (if it’s a subclass) are copied, but objects referenced within those variables are shared:

original = "hello"
copy = original.clone

original.object_id == copy.object_id
# => false - they are different objects

For plain strings, this distinction rarely matters. With custom string subclasses that hold additional state, shallow copy behavior can lead to surprising results if those internal references are later modified.

When to Use Clone vs Dup

Since String#clone is inherited from Object, both methods behave the same on strings for most purposes. The choice comes down to whether you want to preserve frozen status:

  • Use clone when you need to preserve the frozen state of the original string.
  • Use dup when you want a mutable copy regardless of the original’s state.

In practice, most Ruby code uses dup for strings because the shallow copy behavior is sufficient and you typically want a mutable working copy.

Errors

  • TypeError — Strings that are truly unfreezable would raise this, though standard strings do not.

See Also