Frozen string literals and chilled strings

suggest change

In most languages a string literal is a constant. In Ruby it has always been a new, mutable String object, created every time the literal is evaluated. That's convenient (you can << onto ""), but it costs an allocation per evaluation and lets one part of a program change a string another part is still using.

Ruby is moving, slowly, toward frozen string literals:

This article explains each piece, shows how to get a mutable string when you really need one, and walks through making a codebase ready for frozen literals. All examples were run with Ruby 4.0.7. For the general idea of freezing objects see Immutability, and for why shared mutable strings cause bugs see Values and references.

Why freeze string literals

Without the magic comment, each evaluation of a literal creates a new object:

def allocations
  before = GC.stat(:total_allocated_objects)
  yield
  GC.stat(:total_allocated_objects) - before
end

def tag = "item"
p allocations { 100_000.times { tag } }
p tag.equal?(tag)
$ ruby alloc.rb
100003
false

$ ruby --enable-frozen-string-literal alloc.rb
3
true

With frozen literals, "item" is one object stored with the compiled code, and calling tag 100,000 times allocates nothing. The objects are frozen because sharing them is only safe when nobody can change them. See Memory and garbage collection for more on reducing allocations.

The second benefit is correctness. When a method returns a literal and a caller appends to it, a frozen literal raises FrozenError right away instead of letting the change leak into data someone else holds.

The magic comment

Put # frozen_string_literal: true in the first comment section of a file, before any code. A #! line or an encoding comment can come before it. It applies to every literal in that file, and only that file:

# frozen_string_literal: true
a = "x"
p a.frozen?
p "x".equal?("x")
n = 1
b = "n=#{n}"
p b.frozen?
h = <<~TXT
  heredoc
TXT
p h.frozen?
p %w[a b].map(&:frozen?)
p :sym.to_s.frozen?
p 'single'.frozen?, %q(q).frozen?
true
true
false
true
[true, true]
false
true
true

What it covers:

Trying to mutate a frozen literal raises FrozenError:

# frozen_string_literal: true
s = "hello"
s << " world"
frozen.rb:3:in '<main>': can't modify frozen String: "hello" (FrozenError)

You can also write # frozen_string_literal: false. That turns off freezing and chilling for the file, which is how you opt a file out of the warnings described next.

Chilled strings (Ruby 3.4+)

In a file without the magic comment, a string literal is chilled. A chilled string is a mutable string with one extra flag: the first time it's mutated, Ruby emits a deprecation warning and clears the flag. Nothing else changes:

s = "abc"
p s.frozen?
s << "d"
p s
p s.frozen?
$ ruby chilled.rb
false
"abcd"
false

Without warnings enabled, a chilled string behaves exactly like a normal mutable string. frozen? returns false, and there's no public method to ask whether a string is chilled.

Deprecation warnings are off by default. Turn them on with -W:deprecated, or with -w, which enables all warning categories:

$ ruby -W:deprecated chilled.rb
false
chilled.rb:3: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
"abcd"
false

The warning points to the line that mutated the string, not to the literal. You can also enable the category from Ruby code, for example in a test helper:

Warning[:deprecated] = true
s = "text"
s.upcase!
p s
t = "chilled"
t.freeze
p t.frozen?
u = "dup me".dup
u << "!"
w = "abc"
p w + "def", w.upcase, w * 2
warn.rb:3: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
"TEXT"
true
"abcdef"
"ABC"
"abcabc"

This shows what does and doesn't count as mutation:

Each literal evaluation creates a new chilled string, so a literal inside a loop warns on every iteration:

3.times { x = "loop"; x << "!" }
$ ruby -W:deprecated loop.rb
loop.rb:1: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
loop.rb:1: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
loop.rb:1: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)

Heredocs, single-quoted strings, %w[] elements and adjacent literals ("a" "b") are all chilled. Interpolated strings never are:

h = <<~TXT
  heredoc
TXT
h << "more"
w = %w[a b]
w[0] << "x"
q = 'single'
q << "!"
i = "n=#{1}"
i << "!"
c = "a" "b"
c << "!"
p [h, w, q, i, c]
$ ruby -W:deprecated kinds.rb
kinds.rb:4: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
kinds.rb:6: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
kinds.rb:8: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
kinds.rb:12: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
["heredoc\nmore", ["ax", "b"], "single!", "n=1!", "ab!"]

Line 10 (i << "!") has no warning.

Chilled Symbol#to_s

Symbol#to_s returns a new string on every call. Returning a frozen, shared string would be faster, but code like name.to_s << "_id" would break. Ruby 3.4 made these strings chilled too, with a slightly different message:

t = :sym.to_s
t << "x"
p t
$ ruby -W:deprecated sym.rb
sym.rb:2: warning: string returned by :sym.to_s will be frozen in the future
"symx"

The magic comment has no effect on this one, because the string isn't a literal in your file. Symbol#name (Ruby 3.0+) already returns a frozen string, so use name when you only read the result and to_s.dup (or +sym.to_s) when you want to modify it. See Converting a Symbol to String.

Command-line switches

The interpreter has three switches that control literals for every file that has no magic comment:

Switch Effect on literals in files without the comment
(none) chilled; warns on mutation when deprecated warnings are on
--enable-frozen-string-literal frozen, as if every file had # frozen_string_literal: true
--disable-frozen-string-literal plain mutable strings, never chilled, no warning
--debug-frozen-string-literal records where each literal was created, for better messages

--enable=frozen-string-literal is an equivalent spelling. Here's the first chilled example run with each switch:

$ ruby --enable-frozen-string-literal chilled.rb
true
chilled.rb:3:in '<main>': can't modify frozen String: "abc" (FrozenError)

$ ruby -W:deprecated --disable-frozen-string-literal chilled.rb
false
"abcd"
false

A magic comment in a file always wins over the switch, in either direction. A file with # frozen_string_literal: false stays mutable even under --enable-frozen-string-literal, and a file with true is frozen even under --disable-frozen-string-literal.

--disable-frozen-string-literal does not affect Symbol#to_s, which still warns when deprecation warnings are on.

Switches can be passed through the RUBYOPT environment variable, which is how you apply them to rake, rspec or bundle exec without editing anything:

$ RUBYOPT="--enable-frozen-string-literal" ruby -e 'p "x".frozen?'
true
$ ruby -e 'p "x".frozen?'
false

Finding where the string came from

When a string is mutated far from where it was created, the warning's line number isn't enough. --debug-frozen-string-literal makes Ruby remember the creation site of each literal (at some cost in memory and speed, so use it only while debugging):

def make = "buffer"

s = make
s << "!"
$ ruby -W:deprecated --debug-frozen-string-literal debug.rb
debug.rb:4: warning: literal string will be frozen in the future
debug.rb:1: info: the string was created here

$ ruby --enable-frozen-string-literal --debug-frozen-string-literal debug.rb
debug.rb:4:in '<main>': can't modify frozen String: "buffer", created at debug.rb:1 (FrozenError)

The second form is useful in a large test suite: the FrozenError names both the mutation and the literal.

Getting a mutable string

When code needs a string it can modify, say so explicitly. These forms work the same in every mode, so code written with them runs unchanged with chilled literals, frozen literals or neither:

p "x".freeze.equal?("x".freeze)
p "x".equal?("x")
a = -"dyn#{1}"
p a.equal?(-"dyn1")
buf = String.new(capacity: 1024)
p buf.encoding, buf.frozen?
buf2 = String.new("", capacity: 1024)
p buf2.encoding
p (+"lit").frozen?
fr = "fz".freeze
p (+fr).frozen?, (+fr).equal?(fr)
true
false
true
#<Encoding:BINARY (ASCII-8BIT)>
false
#<Encoding:UTF-8>
false
false
false

Deduplicating strings read at runtime looks like this:

names = File.readlines("names.txt", chomp: true)
interned = names.map { -it }
p interned[0].equal?(interned[2])
p interned[0].frozen?
true
true

(names.txt contains alice, bob, alice.)

Files with different settings

The magic comment is per file, but strings flow between files. A library that adopted frozen literals can return a frozen string to a caller that doesn't expect one:

# lib.rb
# frozen_string_literal: true
def greeting = "hello"
# app.rb
require_relative "lib"
s = greeting
p s.frozen?
s << " world"
true
app.rb:4:in '<main>': can't modify frozen String: "hello" (FrozenError)

The fix belongs in the caller, which is the code doing the mutation. Taking a copy is correct no matter how the library is written:

require_relative "lib"
s = greeting.dup
s << " world"
p s
t = +greeting
t << "!"
p t
"hello world"
"hello!"

The general rule: don't mutate strings you didn't create. That rule is good practice anyway, and it's exactly what frozen literals enforce.

The transition plan

The plan, agreed in 2024 (Feature #20205), has three steps:

  1. Ruby 3.4: literals without the comment are chilled and warn when deprecated warnings are enabled.
  2. A later release: turn the warning on by default.
  3. A release after that: make literals frozen by default.

Ruby 4.0 did not take step 2: it behaves like 3.4, and no release has been named for the later steps. Running ruby chilled.rb with no flags on 4.0.7 prints no warning. What changed is that the deprecation is now visible to anyone who looks for it, and gems are expected to fix warnings ahead of the switch.

The magic comment remains the way to opt in today. Once frozen literals become the default, # frozen_string_literal: true will do nothing, and # frozen_string_literal: false will remain the way to opt out for a file.

Making a codebase ready

1. Turn on the warnings in tests. Add -W:deprecated to RUBYOPT in CI, or set Warning[:deprecated] = true in the test helper. To make sure nobody ignores them, turn the chilled-string warning into an exception by overriding Warning.warn:

module FailOnChilledMutation
  def warn(message, category: nil, **)
    if category == :deprecated && message.include?("will be frozen in the future")
      raise FrozenError, message.sub(/ \(run with.*/m, "")
    end
    super
  end
end

Warning.singleton_class.prepend(FailOnChilledMutation)
Warning[:deprecated] = true

def bullet_list(items, out = "")
  items.each { |item| out << "- " << item << "\n" }
  out
end

begin
  bullet_list(%w[a b])
rescue FrozenError => e
  puts "FrozenError: #{e.message}"
end

puts bullet_list(%w[a b], +"")
FrozenError: test_helper.rb:14: warning: literal string will be frozen in the future
- a
- b

The exception is raised at the mutation, so the test failure has a backtrace that points at the code to fix. Note the default argument out = "": it's a literal, so mutating it is exactly the kind of code that will break. Write out = +"" instead.

2. Run the suite with frozen literals. RUBYOPT="--enable-frozen-string-literal --debug-frozen-string-literal" bundle exec rake test simulates the future default for every file without a magic comment, including your gems. FrozenErrors in your own files are bugs to fix now. Errors in gems tell you which dependencies to update or report.

3. Fix the mutations. The common patterns:

Before After
buf = "" then buf << x buf = +"" or buf = String.new("", capacity: n)
def m(out = "") mutating out def m(out = +"")
s = other_method; s << x s = other_method.dup; s << x
name.to_s << "_id" "#{name}_id" or name.to_s + "_id"
str.gsub!(...) on a literal str = str.gsub(...)
s.force_encoding(...) on a literal s = s.dup.force_encoding(...) or String.new(s, encoding: ...)

Often the cleanest fix is to avoid mutation entirely: build the result with interpolation, +, Array#join or map (see String concatenation), and keep << for real buffers where performance matters.

4. Add the magic comment. Once the suite runs clean with the warnings on, add # frozen_string_literal: true to each file. You get the allocation savings today, and a file with the comment no longer depends on the global switch. RuboCop's Style/FrozenStringLiteralComment cop (enabled by default) reports files without it:

def report(rows)
  out = ""
  rows.each { |r| out << r << "\n" }
  out
end
$ rubocop --only Style/FrozenStringLiteralComment report.rb
Inspecting 1 file
C

Offenses:

report.rb:1:1: C: [Correctable] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
def report(rows)
^

1 file inspected, 1 offense detected, 1 offense autocorrectable

The autocorrection is marked unsafe, so plain rubocop -a leaves the file alone and only rubocop -A adds the comment. It's unsafe for a good reason: adding the comment to this file without fixing out = "" turns working code into a crash:

$ rubocop -A --only Style/FrozenStringLiteralComment report.rb
...
1 file inspected, 1 offense detected, 1 offense corrected

$ ruby -e 'load "./report.rb"; puts report(%w[a b])'
report.rb:4:in 'block in Object#report': can't modify frozen String: "" (FrozenError)

That's why the order matters: fix mutations first (steps 1 to 3), then add comments, ideally file by file with the tests running.

Summary

Feature Since What it does
# frozen_string_literal: true 2.3 literals in the file are frozen and deduplicated
# frozen_string_literal: false 2.3 literals in the file are plain mutable strings (no chilling)
interpolated strings not frozen 3.0 "a#{b}" is always a new mutable string
chilled literals 3.4 no comment: mutable, warns on first mutation under -W:deprecated
chilled Symbol#to_s 3.4 warns when the returned string is mutated
--enable-frozen-string-literal 2.3 freeze literals in every file without a comment
--disable-frozen-string-literal 2.3 plain mutable literals; since 3.4 also turns chilling off
--debug-frozen-string-literal 2.3 report where the frozen or chilled string was created
Ruby 4.0 4.0 same as 3.4: still chilled, warning still opt-in

To get a mutable string, use +"...", .dup or String.new("", capacity: n). To get a frozen shared one, use -str or .freeze. And don't mutate strings your code didn't create.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents