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

freeze

In this page:

  1. freeze

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
🔒

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.