freeze
freeze locks an object so it cannot be changed, like putting a sculpture behind glass. Any attempt to alter it afterwards raises an error.
In this page:
Syntax
CONSTANT = "value".freeze
object.frozen?
freeze
.freeze makes an object immutable, so any attempt to modify it afterward raises a FrozenError.
String literals are mutable by default in Ruby (unlike some languages), so freeze is used explicitly when you want to guarantee a string never changes. Freezing is also commonly applied to constants to prevent accidental mutation.
Note:
# frozen_string_literal: true as the first line of a file makes every string literal in it frozen by default.Example: freeze
name = "Alice".freeze
puts name.frozen?
begin
name << " Smith"
rescue => e
puts "Error: #{e.class}"
end
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Assuming
freezemakes a whole nested structure immutable, when it freezes only the object and its contents can still change. - Trying
name << " Smith"on a frozen string, which raisesFrozenError; usename + " Smith"instead. - Freezing a variable's value and thinking the variable cannot be reassigned, when
name = "Bob"still works.
Chapter Summary
- Strings have many methods, and multiline strings and heredocs handle longer text.
- String formatting,
gsub,sub,split, andjointransform text. freezeprevents a string from being modified.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: