Ruby: Why freeze mutable objects assigned to constants?
Solution 1
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.
Solution 2
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
Related videos on Youtube
Comments
-
american-ninja-warrior almost 2 years
Consider this offense reported by rubocop
lib/awesomelib/aws.rb:6:10: C: Style/MutableConstant: Freeze mutable objects assigned to constants. IP = '34.111.241.111' ^^^^^^^^^^^^^^^^
Why should I freeze this IP address?
-
wintersolutions over 5 yearsNote:
IP = '192.168.1.1'
is still possible and will still result in a warning, not a error.