Ruby: Why freeze mutable objects assigned to constants?
Freezing an object means you are no longer allowed to mutate it. A constant means you are no longer allowed to mutate the binding. (Well, okay, you get a warning if you mutate the binding.) The two just go together well.
In particular, the fact that a mutable object assigned to an immutable binding can still be mutated, might be confusing to some. Just witness the various questions on Stack Overflow about it:
IP = '34.111.241.111'
# Dis is a constant, I can never change it, amirite?
IP << '.255'
IP
#=> '34.111.241.111.255'
# Ooops!
IP.freeze
IP << '.255'
# RuntimeError: can't modify frozen String
You should freeze the value assigned to IP
because you've declared IP
to be a constant. This indicates that you don't want the value assigned to IP
to be mutated.
The problem is that in ruby, assigning a value to a constant does not make the value immutable. You just get a warning if you mutate the value assigned to the constant. To make the value actually immutable, you need to .freeze
the value assigned to the constant. After you've frozen a value assigned to a constant, if you try to change the value, you will hit a runtime error.