LoginSignup
36
11

More than 1 year has passed since last update.

Rubyで #frozen_string_literal: true というマジックコメントを付ける意味

Last updated at Posted at 2021-06-15

Rubyで開発する時、rubocopを使ったらよく Missing frozen string literal comment と警告され、ファイルの一番上に「#frozen_string_literal: true」を入れることが推進されます。

簡単に説明すると、Ruby 2.3以降では、#frozen_string_literal: trueというマジックコメントを記述した場合、文字列リテラルで生成される文字列は値が変更できないようにfreezeされ、同じ内容の文字列リテラルは同一の文字列オプジェクトを返すようになります。

#frozen_string_literal: true がない場合

text1 = 'Hello world'
text2 = 'Hello world'

puts text1.object_id == text2.object_id

文字列の内容が同じでもオブジェクトが別の為、falseを返します。

#frozen_string_literal: true がある場合

#frozen_string_literal: true

text1 = 'Hello world'
text2 = 'Hello world'

puts text1.object_id == text2.object_id

同じ内容の文字列は同一の文字列オブジェクトなので、trueを返します。

36
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
11