Ruby: What does the comment “frozen_string_literal: true” do?

# frozen_string_literal: true is a magic comment, supported for the first time in Ruby 2.3, that tells Ruby that all string literals in the file are implicitly frozen, as if #freeze had been called on each of them. That is, if a string literal is defined in a file with this comment, and you call a method on that string which modifies it, such as <<, you’ll get RuntimeError: can't modify frozen String.

Freezing strings prevents bugs caused by accidentally modifying a string when you didn’t intend to, and may improve performance.

Like any magic comment, the frozen_string_literal comment must be in the first comment section of the file. Ironically, the frozen_string_literal comment in that binstub is not in the binstub’s first comment section and will be ignored.

In Ruby 2.3, you can use this magic comment to prepare for frozen string literals being the default in Ruby 3.

In Ruby 2.3 run with the --enable=frozen-string-literal flag, and in Ruby 3, string literals are frozen in all files. You can override the global setting with # frozen_string_literal: false.

If you want a string literal to be mutable regardless of the global or per-file setting, you can prefix it with the unary + operator (being careful with operator precedence) or call .dup on it:

# frozen_string_literal: true
"".frozen?
=> true
(+"").frozen?
=> false
"".dup.frozen?
=> false

You can also freeze a mutable (unfrozen) string with unary -.

Source: magic_comment defined in ruby/ruby

Leave a Comment