# 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
.
The comment must be on the first line of the file.
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 -
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…