← Back to Ruby Course | Chapter 3: Strings | Lesson 7 of 7

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:

  1. freeze
Syntax
ruby
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

markup
name = "Alice".freeze

puts name.frozen?

begin
  name << " Smith"
rescue => e
  puts "Error: #{e.class}"
end
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
  1. Assuming freeze makes a whole nested structure immutable, when it freezes only the object and its contents can still change.
  2. Trying name << " Smith" on a frozen string, which raises FrozenError; use name + " Smith" instead.
  3. 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, and join transform text.
  • freeze prevents a string from being modified.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.