← Back to Ruby Course | Chapter 12: Ruby Best Practices | Lesson 2 of 6

Frozen String Literals

In this page:

  1. Frozen String Literals

Frozen String Literals

Adding # frozen_string_literal: true as the very first line of a Ruby file makes every string literal in that file frozen (immutable) by default, which can improve performance by avoiding unnecessary string object allocation. This is now a common convention in Ruby projects and gems. Individual strings can still be explicitly unfrozen by calling .dup to get a mutable copy.

Note: Call .dup on a frozen string if you specifically need a mutable copy of it.

Example: Frozen String Literals

markup
# frozen_string_literal: true

name = "Alice"
puts name.frozen?

mutable_copy = name.dup
puts mutable_copy.frozen?
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 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.