HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyCritical

Ruby: What does the comment "frozen_string_literal: true" do?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
thefrozen_string_literalrubydoestruewhatcomment

Problem

This is the rspec binstub in my project directory.

#!/usr/bin/env ruby
begin
  load File.expand_path("../spring", __FILE__)
rescue LoadError
end
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'rspec' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
  Pathname.new(__FILE__).realpath)

require "rubygems"
require "bundler/setup"

load Gem.bin_path("rspec-core", "rspec")


What is this intended to do?

# frozen_string_literal: true

Solution

# 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 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

Code Snippets

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

Context

Stack Overflow Q#37799296, score: 549

Revisions (0)

No revisions yet.