user3417583
user3417583

Reputation: 1437

Why freezing hash values before freezing the hash itself?

I have noticed that some folks do { 'foo': 'bar'.freeze }.freeze instead of just { 'foo': 'bar' }.freeze.

Is it better? If so, why?

Upvotes: 1

Views: 1248

Answers (1)

BroiSatse
BroiSatse

Reputation: 44685

hash.freeze freezes hash itself, but not its values. This means you will no longer be able to assign new values or delete keys, but you can still mutate the existing values:

hash = {a: 'hello'}.freeze
hash[:b] = 'there' #=> exception!
hash[:a] = 'hello there' #=> exception!
hash[:a].upcase! #=> no exception
hash #=> {a: 'HELLO'}

On the third line we try to assign a new string to an existing key, which fails. But on a fourth line we directly modify the instance of the string. Hash is just keeping references to other objects, so modifying a string does not affect hash at all.

Things are different if you also freeze the string:

hash = {a: 'hello'.freeze}.freeze
hash[:a].upcase! #=> exception!

Upvotes: 2

Related Questions