3 ms·
Freeze your constants!
by mwpmaybe 10y ago
Freeze your constants!
- busterarm 10y agoI used to do this with strings (now you don't have to), but this is great advice!
- mwpmaybe 10y agoYeah, it's one of those rare Ruby gotchas. If you assign some kind of a data structure to a constant, you'll get a warning if you try to reassign the constant, but the data structure itself will silently mutable. To disallow this behavior, simply freeze the data structure. If you have nested data structures, you must freeze deeply. ENUM = [0, 1, 2].freeze LOOKUP = { :A => [1, 2, 3].freeze, :B => [4, 5, 6].freeze }.freeze # or: LOOKUP = { :A => [1, 2, 3], :B => [4, 5, 6] }.tap { |s| s.values.each(&:freeze) }.freeze