What is Frozen String Literal
We have seen this comment # frozen_string_literal: true
in our Ruby files,
have you ever wondered what exactly this comment does?
In Ruby, a literal string is a sequence of characters enclosed in single (‘’) or double (“”) quotes. These strings are mutable, meaning their contents can be modified after creation.
The magic comment # frozen_string_literal: true
in Ruby instructs the Ruby
interpreter to freeze all string literals. This means that each string literal is
allocated memory only once and cannot be modified.
This improves memory efficiency and prevents accidental changes to string values throughout the program.
Magic comments are special comments in Ruby that are specified on top of the file. They influence how the Ruby code is executed, essentially providing instructions for the Ruby interpreter to follow specific behaviors based on the comments provided.
Note: The magic comment # frozen_string_literal: true
was supported first time in Ruby 2.3
Now let’s see in the example below how the String is mutable.”
But when we use a frozen literal string comment, we get the FrozenError
As we have mentioned before it improves memory efficiency as well, memory allocations, which means memory should be allocated only once for each string literal.
We can see below that if we are not using the magic comment then allocated memory is different for the same string.
But when we use the magic comment, it allocates the memory only once for the same string. In the below example, we can see that the object_id is the same for the string “Ruby on Rails” every time.
From Ruby 3.4 frozen_string_literal is enabled by default
Now in Ruby 3.4 string
literals in files without a # frozen_string_literal: true
comment now
behave as if they were frozen. If they are mutated, a deprecation warning is emitted.
But the warnings are not emitted by default, we have to enable it by setting Warning[:deprecated] = true. The reason is deprecation warnings should only be useful during development for updating Ruby code, and should not be displayed continuously.
To disable the behavior where string literals are treated as frozen by default in Ruby,
we can use the --disable-frozen-string-literal
command line
argument when running the Ruby script.
Please go through this link to read more about it.