TIL, 2018-08-07, freeze and frozen in Ruby
When to use
frozen? in Ruby
- Creating immutable constants: in Ruby, by default, constants are immutable, when you freeze the constant, then it really is actually constant.
- Reducing object allocations:
log('foobar')creates a new String object.
log('foobar'.freeze)caches the String for future use. Example: Rails router. It has
- Ruby 2.2: automatically freezes string literals that are used as hash keys.
- Ruby 3: all string literals will be frozen automatically in Ruby 3.
- You can call
freezein a constructor just to make sure that the object will never change.
class Point attr_accessor :x, :y def initialize(x, y) @x = x @y = y freeze end def change @x = 3 end end point = Point.new(1,2) point.change # RuntimeError: can't modify frozen Point
7 Things to Start Being More Productive, Today Reference Being productive: time management and managing your energy. Spending the least...