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

Frozen String Literals

A special comment at the very top can make every text in the file locked so it cannot be changed. It is like laminating all your notes so no one can scribble on them.

In this page:

  1. Frozen String Literals
Syntax
ruby
# frozen_string_literal: true

string = "literal"    # frozen, cannot be modified

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?
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. Placing the # frozen_string_literal: true comment after other lines, when it must be at the top to work.
  2. Modifying a string with << afterwards, which raises FrozenError; use dup or +"".
  3. Believing it freezes interpolated strings in all cases, when it applies only to literals without interpolation.
🔒

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.