Ruby: Why freeze mutable objects assigned to constants?

american-ninja-warrior picture american-ninja-warrior · Nov 1, 2017 · Viewed 9.8k times · Source

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?

Answer

jk_ picture jk_ · Nov 1, 2017

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.