Ruby:注释"frozen_string_literal:true"是什么意思?做? [英] Ruby: What does the comment "frozen_string_literal: true" do?

查看:128
本文介绍了Ruby:注释"frozen_string_literal:true"是什么意思?做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我项目目录中的rspec容器.

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")

这打算做什么?

# frozen_string_literal: true

推荐答案

# frozen_string_literal: true是一个魔术注释,在Ruby 2.3中首次受支持,它告诉Ruby文件中的所有字符串文字都被隐式冻结,就像#freeze分别被调用了.也就是说,如果在带有此注释的文件中定义了字符串文字,并且您在该字符串上调用了对其进行修改的方法(例如<<),则会得到RuntimeError: can't modify frozen String.

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

在Ruby 2.3中,您可以使用此魔术注释来准备冻结字符串字面量,这是Ruby 3中的默认值.

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

在运行--enable=frozen-string-literal标志的Ruby 2.3中,;在Ruby 3中,字符串文字被冻结在所有文件中.您可以使用# frozen_string_literal: false覆盖全局设置.

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.

如果您希望字符串文字是可变的,而不管全局设置或每个文件设置如何,都可以在其前加上一元+运算符(请注意运算符的优先级)或在其上调用.dup: >

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

这篇关于Ruby:注释"frozen_string_literal:true"是什么意思?做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆