# frozen_string_literal: true is a magical comment first supported in Ruby 2.3 that tells Ruby that all string literals in a file are implicitly frozen, as if #freeze were called for each of them. That is, if a string literal is defined in a file with this comment, and you call a method for this string that modifies it, for example << , you will get RuntimeError: can't modify frozen String .
The comment should be in the first line of the file.
In Ruby 2.3, this magic commentary can be used to prepare for fixed string literals, which are used by default in Ruby 3 .
In Ruby 2.3, it starts with --enable=frozen-string-literal , and in Ruby 3, string literals are committed to all files. You can override the global setting with # frozen_string_literal: false .
If you want the string literal to be mutable regardless of global or file settings, you can prefix it with the unary + operator (carefully with operator precedence) or call .dup for it:
# frozen_string_literal: true "".frozen? => true (+"").frozen? => false "".dup.frozen? => false
You can also freeze a mutable (non-freezing) string with unary - .
Dave Schweisguth Jun 13 '16 at 21:26 2016-06-13 21:26
source share