All Articles

Magic frozen string literal comment in Ruby 2.3

In Ruby 2.3, string immutability is opted in with the magic comment on the top of the file. Adding the magic comment on the file tells Ruby that all the strings in the file are implicitly frozen(immutable).

# frozen_string_literal: true

Immutability means the state of the object cannot be changed. In Ruby 2.3 without the magic comment, if a string literal is defined and its value is changed then its state would be successfully mutated and method would return newly assigned value.

def something
  string_1 = 'Abhay'
  string_1 = 'Aryan'

> Output: Aryan

Whereas if we have added the magic comment on the top of the file and if a string literal value is tried to mutate then Ruby would throw an error.

> can't modify frozen String

Also with Ruby 3.0, Matz - Creator of Ruby has decided to make all the string literal in the Ruby immutable by default. Here is the relevant issue.

Making string immutable by default would increase the performance and program will run faster as unwanted data duplication would be reduced. This will also help in the garbage collection as GC would require less time destroying the objects. But making string literal immutable by default also have an impact on the 3rd party gems. Let’s say a gem try to mutate the string literal, Ruby would throw an error.

To adapt this new feature would require time but, once done the transition would be much smoother.

But till the time Ruby 3.0 comes, we can achieve this by adding the Magic comment in the file.

Happy Coding!!