Let’s consider the very simple ruby method which takes a country code and returns a country name. I’m sure that many of us write similar methods, especially at the beginning of the Ruby journey.

class SampleClass
  def country_name(country_code:)
    mappings = {
      'us' => 'USA',
      'de' => 'Germany'
    }

    mappings[country_code]
  end
end

Want to receive useful tips, information about new Ruby gems and articles on a daily basis? Make sure you follow me and say hello!

To make things more readable we can move mappings outside the method. Moving them to the separated method is ok. Moving them to the constant is good. But moving them to the frozen constant is perfect because it saves some memory for us:

class SampleClass
  COUNTRY_CODES_MAPPINGS = {
    'us' => 'USA',
    'de' => 'Germany'
  }.freeze

  def country_name(country_code:)
    COUNTRY_CODES_MAPPINGS[country_code]
  end
end

Without freezing our constant you will be able to change its value but with a frozen constant you can’t do it - you will experience RuntimeError. Generally, freezing also saves memory for us because it reduces memory allocation.

What’s interesting with Ruby 2.2 string literals used in hash keys are automatically frozen.

Special thanks to my workmate, Darek, who showed me this trick.

Want to become a better Rails developer?
Download for free the Introduction Rails patterns book and dive into the world of refactoring and easy-testable Ruby code today.
Join over 1,000 developers already subscribed to my newsletter and download the book. You can unsubscribe anytime:

Subscribe and get the book!