String#freeze

str.freeze -> str
Returns: String · Updated March 13, 2026 · String Methods
immutability memory strings performance

The freeze method marks an object as immutable. Once frozen, any attempt to modify the object will raise a FrozenError. Strings in Ruby are frozen by default since Ruby 3.0, but you can explicitly freeze mutable objects to prevent accidental modifications.

Syntax

str.freeze

Parameters

freeze takes no parameters. It operates on the receiver object directly.

Examples

Basic usage

s = "hello"
s.freeze

begin
  s << " world"
rescue FrozenError => e
  puts e.message
end
# => can't modify frozen String

Working with string literals

# In Ruby 3.0+, string literals are automatically frozen
"hello".frozen?  # => true

# Create a mutable string with dup
s = "hello".dup
s.frozen?        # => false
s << " world"    # works fine
s                # => "hello world"

Freeze for memory efficiency

# Reusing a frozen string literal saves memory
urls = Array.new(1000) { "https://example.com" }
urls.each(&:object_id).uniq.size  # => 1 (all point to same frozen string)

# If you need unique strings, they each consume memory
unique_urls = Array.new(1000) { "https://example.com".dup }
unique_urls.each(&:object_id).uniq.size  # => 1000

Common Patterns

Protecting configuration

CONFIG = {
  max_retries: 3,
  timeout: 30
}.freeze

CONFIG[:max_retries] = 5  # => FrozenError

Freezing arrays and hashes

# Freeze composite objects to make them immutable
colors = ["red", "green", "blue"].freeze
colors << "yellow"  # => FrozenError

settings = { env: "production", debug: false }.freeze
settings[:new_key] = true  # => FrozenError

Deduplication with freeze

# Force string deduplication
symbols = %w[foo bar baz].map(&:freeze).map(&:to_sym)
# Creates symbols: :foo, :bar, :baz

Errors

ErrorWhen it occurs
FrozenErrorAttempting to modify a frozen object

See Also