When to use freeze and frozen? in Ruby

These days it's pretty common to see #freeze used in Ruby code. But it's often not entirely clear WHY freeze is being used. In this post we'll look at the most common reasons a developer might freeze variables.

These days it's pretty common to see #freeze used in Ruby code. But it's often not entirely clear WHY freeze is being used. In this post we'll look at the most common reasons a developer might freeze variables. To illustrate each reason, I've excerpted example code from the Rails codebase and other popular open-source projects.

Creating immutable constants

In Ruby, constants are mutable. It's a little confusing, but the code is easy enough to understand. Here, I've created a string constant and am appending another string to it.

MY_CONSTANT << "bar"
puts MY_CONSTANT.inspect # => "foobar"

By using #freeze, I'm able to create a constant that's actually constant. This time, when I attempt to modify the string, I get a RuntimeError.

MY_CONSTANT = "foo".freeze
MY_CONSTANT << "bar" # => RuntimeError: can't modify frozen string

Here' a real-world example of this in the ActionDispatch codebase.  Rails hides sensitive data in logs by replacing it with the text "[FILTERED]". This text is stored in a frozen constant.

module ActionDispatch
  module Http
    class ParameterFilter
      FILTERED = '[FILTERED]'.freeze

Reducing object allocations

One of the best things you can do to speed up your Ruby app is to decrease the number of objects that are created. One annoying source of object allocations comes from the string literals that are sprinkled throughout most apps.

Every time you do a method call like log("foobar"), you create a new String object. If your code calls a method like this thousands of times per second, that means you're creating (and garbage-collecting) thousands of strings per second. That's a lot of overhead!

Fortunately, Ruby gives us a way out. If we freeze string literals, the Ruby interpreter will only create one String object and will cache it for future use. I've put together a quick benchmark showing the performance of frozen vs. non-frozen string arguments. It shows around a 50% performance increase.

require 'benchmark/ips'

def noop(arg)

Benchmark.ips do |x|
  x.report("normal") { noop("foo") }
  x.report("frozen") { noop("foo".freeze)  }

# Results with MRI 2.2.2:
# Calculating -------------------------------------
#               normal   152.123k i/100ms
#               frozen   167.474k i/100ms
# -------------------------------------------------
#               normal      6.158M (± 3.3%) i/s -     30.881M
#               frozen      9.312M (± 3.5%) i/s -     46.558M

You can see this in action if you look at the Rails router. Since the router is used for every web page request, it needs to be fast. That means a lot of frozen string literals.

# excerpted from https://github.com/rails/rails/blob/f91439d848b305a9d8f83c10905e5012180ffa28/actionpack/lib/action_dispatch/journey/router/utils.rb#L15
def self.normalize_path(path)
  path = "/#{path}"
  path.sub!(%r{/+\Z}, ''.freeze)
  path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase }
  path = '/' if path == ''.freeze

Built-in optimizations in Ruby >= 2.2

Ruby 2.2 and later (MRI) will automatically freeze string literals that are used as hash keys.

user = {"name" => "george"}

# In Ruby >= 2.2

# ...is equivalent to this, in Ruby <= 2.1

And according to Matz, all string literals will be frozen automatically in Ruby 3.

Value objects & functional programming

While Ruby isn't a functional programming language, many Rubyists have begun to see the value of working in a functional style. One of the main tenets of this style is that you should avoid side effects. Objects should never change after they've been initialized.

By calling the freeze method inside the constructor, it's possible to guarantee that an object will never change. Any unintentional side-effects will result in an exception being raised.

class Point
  attr_accessor :x, :y
  def initialize(x, y)
    @x = x
    @y = y

  def change
    @x = 3

point = Point.new(1,2)
point.change # RuntimeError: can't modify frozen Point
What to do next:
  1. Try Honeybadger for FREE
    Honeybadger helps you find and fix errors before your users can even report them. Get set up in minutes and check monitoring off your to-do list.
    Start free trial
    Easy 5-minute setup — No credit card required
  2. Get the Honeybadger newsletter
    Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you.
    author photo

    Starr Horne

    Starr Horne is a Rubyist and Chief JavaScripter at Honeybadger.io. When she's not neck-deep in other people's bugs, she enjoys making furniture with traditional hand-tools, reading history and brewing beer in her garage in Seattle.

    More articles by Starr Horne
    Stop wasting time manually checking logs for errors!

    Try the only application health monitoring tool that allows you to track application errors, uptime, and cron jobs in one simple platform.

    • Know when critical errors occur, and which customers are affected.
    • Respond instantly when your systems go down.
    • Improve the health of your systems over time.
    • Fix problems before your customers can report them!

    As developers ourselves, we hated wasting time tracking down errors—so we built the system we always wanted.

    Honeybadger tracks everything you need and nothing you don't, creating one simple solution to keep your application running and error free so you can do what you do best—release new code. Try it free and see for yourself.

    Start free trial
    Simple 5-minute setup — No credit card required

    Learn more

    "We've looked at a lot of error management systems. Honeybadger is head and shoulders above the rest and somehow gets better with every new release."
    — Michael Smith, Cofounder & CTO of YvesBlue

    Honeybadger is trusted by top companies like:

    “Everyone is in love with Honeybadger ... the UI is spot on.”
    Molly Struve, Sr. Site Reliability Engineer, Netflix
    Start free trial