Today I Learned

TIL, 2018-08-07, freeze and frozen in Ruby

When to use freeze and frozen? in Ruby

Reference

  • 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 freeze everywhere.
  • 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 freeze in 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
  • AppSetting.pluck("DISTINCT account_id")

This project is maintained by daryllxd