×

ruby · level 3 · unit 7 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

locks an object so nothing can change it.

Some values must never change: the list of valid statuses, a tax rate, the settings loaded at start-up. Call freeze and the object is locked, and frozen? tells you whether it is. Any attempt to change it, such as adding an item with <<, raises and points straight at the culprit.

Freezing is shallow: a frozen array can still hold strings that change, so freeze each item too, with map(&:freeze). Rails models keep their fixed lists in frozen constants. When you need a version you can change, makes an unfrozen copy and leaves the original locked.

STATUSES = ["draft", "live", "archived"].map(&:freeze).freeze
p STATUSES.frozen?
p STATUSES.first.frozen?
copy = STATUSES.dup
copy << "deleted"
p copy
p STATUSES
begin
  STATUSES << "deleted"
rescue FrozenError => error
  puts error.message
end

Symbols, whole numbers and nil are always frozen, which is one reason they make safe hash keys.