FrozenError
RubyERRORNotableMutation
Attempt to modify a frozen object
Quick Answer
Call .dup or .clone to get a mutable copy of a frozen object before modifying it.
What this means
Raised when code attempts to modify an object that has been frozen with Object#freeze. FrozenError is a subclass of RuntimeError. String literals are frozen by default when frozen_string_literal: true is set.
Why it happens
- 1Modifying a string literal when frozen_string_literal: true is enabled
- 2Calling mutating methods (<<, gsub!, push) on an explicitly frozen object
- 3Modifying a frozen Hash or Array in a shared/constant context
Fix
Duplicate before mutating
Duplicate before mutating
CONSTANT = 'hello'.freeze def shout(str) str.dup.upcase! # dup gives a mutable copy end shout(CONSTANT) # safe
Why this works
dup creates an unfrozen shallow copy, allowing mutation without affecting the original frozen object.
Code examples
Reproducing the errorruby
str = 'hello'.freeze str << ' world' # FrozenError: can't modify frozen String: "hello"
frozen_string_literal magic commentruby
# frozen_string_literal: true str = 'hello' str << '!' # FrozenError
Using dup to safely mutateruby
mutable = frozen_str.dup mutable << ' appended'
Same error in other languages
Sources
Official documentation ↗
Ruby Core Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev