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

后端 未结 3 1775
南笙
南笙 2020-11-30 17:47

This is the rspec binstub in my project directory.

#!/usr/bin/env ruby
begin
  load File.expand_path(\"../spring\", __FILE__)
rescue LoadError
e         


        
3条回答
  •  伪装坚强ぢ
    2020-11-30 18:09

    In Ruby 3.0. Matz (Ruby’s creator) decided to make all String literals frozen by default.

    EDIT 2019: he decided to abandon the idea of making frozen-string-literals default for Ruby 3.0 (source: https://bugs.ruby-lang.org/issues/11473#note-53)


    You can use in Ruby 2.x. Just add this comment in the first line of your files.

    # frozen_string_literal: true
    

    The above comment at top of a file changes semantics of static string literals in the file. The static string literals will be frozen and always returns same object. (The semantics of dynamic string literals is not changed.)

    This way has following benefits:

    No ugly f-suffix. No syntax error on older Ruby. We need only a line for each file.

    Plese, read this topic for more information.

    https://bugs.ruby-lang.org/issues/8976

提交回复
热议问题