frozen / freeze (Ruby)
Calling freeze on an object makes it immutable — any attempt to modify it raises a FrozenError. Frozen objects are safer to share and let Ruby optimize, especially for string literals.
Ruby
obj.freeze prevents further mutation of that object; freeze returns the object and frozen? reports its state. It's a shallow freeze — the object itself can't change, but objects it references still can unless they're frozen too.
Freezing is most associated with strings. Because strings are mutable by default, identical literals each allocate a new object; the magic comment # frozen_string_literal: true at the top of a file makes all string literals frozen, saving memory and preventing accidental mutation. Symbols and small integers are effectively always frozen.
Freeze constants and shared configuration to catch accidental modification early, and to make objects safe to share across threads. It's a lightweight way to express and enforce immutability in Ruby.
Syntax
value.freeze
value.frozen? # => trueExamples
Ruby
s = "hello".freeze
puts s.frozen?
begin
s << " world"
rescue => e
puts e.class
endOutput:
true
FrozenError