Skip to content

Instantly share code, notes, and snippets.

@dissolved
Last active March 3, 2020 14:55
Show Gist options
  • Save dissolved/245a445f86e229f87eb9e083f0d1bb98 to your computer and use it in GitHub Desktop.
Save dissolved/245a445f86e229f87eb9e083f0d1bb98 to your computer and use it in GitHub Desktop.
A micropost about freezing unnecessarily

Cargo Culting Ruby's freeze

Years ago you rarely saw frozen Ruby objects, but it is very much popular now. There are good reasons to freeze. Take this commonly cited example:

MOVIE = "Not Frozen"
MOVIE << " II" # note no warning because MOVIE is not reassigned, but rather the string is mutated
puts MOVIE # "Not Frozen II"

So the solution to this problem is to freeze the string.

BETTER_MOVIE = "Frozen".freeze
BETTER_MOVIE << " II" # FrozenError: can't modify frozen String
puts BETTER_MOVIE # "Frozen"

There is another reason to freeze strings that aren't expected to ever change, and that involves memory allocation. A frozen string uses the same memory optimization that symbols use. And there are other objects you do want to freeze when you assign them to a constant that isn't expected to change, including but not limited to Hashes, Arrays, or any object that may mutate its internal state.

But these days people are freezing all constants, even when they are immutable to begin with. For example, there is no reason (that I am aware of) to freeze an ActiveSupport::Duration.

GRACE_PERIOD = 28.days.freeze # this is unnecessary

There is nothing that I am aware of that you can do to GRACE_PERIOD here that would mutate its value. Of course, we can still reassign it because constants in Ruby are a suggestion not a rule.

GRACE_PERIOD = 30.days.freeze # warning: already initialized constant GRACE_PERIOD

But as you can see, freezing has no impact on the ability to reassign the value of a constant in Ruby.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment