Frozen String Literals
In this page:
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
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: