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.