dCSeven
dCSeven

Reputation: 905

Ruby: magic comments "frozen_string_literal: true" vs "immutable: string"

In ruby one can freeze all constant strings in a file via two different magic comments at the beginning of a file:

# frozen_string_literal: true

and

# -*- immutable: string -*-

I have no idea what the differences are. Are there any?

Upvotes: 6

Views: 2827

Answers (2)

lacostenycoder
lacostenycoder

Reputation: 11186

Digging for anything on the 2nd version, it looks like they had the same intention but the 2nd magic comment syntax does not to appear to have been adopted as of Ruby 2.1.0.

The first version # frozen_string_literal: true was adopted in Ruby 2.3.0

I tried the latter version in a few versions of Ruby but didn't work. I would guess it should not be used or trusted to work in any version of >= 2.3 but probably no versions support it. In fact, I was not able to find any reference to that version in the open source code on GitHub searching that syntax.

Upvotes: 3

user9903
user9903

Reputation:

The 1st syntax is the magic comment for Ruby 2.3+ versions to freeze string literals, otherwise you have to use the String method like this:

'hello world!'.freeze

The 2nd syntax is not implemented in Ruby, however it is the way that variables are specified for files in the Emacs text editor.

For example, the following comment in Emacs would declare that the file is a Ruby file and needs Ruby syntax highlighting, and that the variable immutable is set to the value string.

# -*- mode: ruby; immutable: string -*-

After searching around, it looks like that does nothing and is not used by any Ruby syntax highlighting mode.

So you do not need the 2nd syntax.

Upvotes: 7

Related Questions