Skip to content
Lucas Caton

What is "frozen_string_literal" in Ruby?

Why use this magic comment?

Lucas Caton

Lucas Caton

@lucascaton
Freezing Strings feature improves apps performance by freezing Strings. So, Matz, Ruby's creator, decided to make all String literals frozen (immutable) by default in Ruby 3.0. Update: the Ruby team changed their mind and this didn't happen when Ruby 3.0 was released.
In order to have a transition path to this coming big change, it was decided to have a magic comment at the beginning of files, so you can use in Ruby 2.x. To do so, just add this comment in the first line of your files:
ruby
# frozen_string_literal: true
class YourClass
  # ...
end
Try adding it to your spec_helper or rails_helper file and let me know in the comments if your performance gets any better.

More info: Ruby issue #8976.

Post updated at 11/09/2024, 10:00:00