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:
Syntax
# 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
# frozen_string_literal: true
name = "Alice"
puts name.frozen?
mutable_copy = name.dup
puts mutable_copy.frozen?
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
- Placing the
# frozen_string_literal: truecomment after other lines, when it must be at the top to work. - Modifying a string with
<<afterwards, which raisesFrozenError; usedupor+"". - 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: