ruby · level 3 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
The team is frozen. Can a name still change?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
team = ["Ana", "Ben"].freeze
team[0] << "bel"
p team
p team.frozen?
p team[0].frozen?
your turn
Your turn. Lock the defaults, then change a copy.
Freeze the defaults in the first blank and make a changeable copy in the second. Then pick a theme of your own in the third.
fix it
The frozen tags caught a bug. Fix the method.
- The constant is frozen, so
<<on it fails. Do you really want to changeDEFAULT_TAGS? tags = DEFAULT_TAGScopies nothing. Both names point at the same frozen array.- Change line 3 to
tags = DEFAULT_TAGS.dup, then press run.
nailed it
you froze what must not change. :D
freezelocks an object, and changing it raises FrozenError.- Freezing is shallow, so freeze the items as well.
dupmakes an unfrozen copy you can change safely.
new words in your collection
- freeze
- FrozenError
- dup
This lesson isn’t saved. A free account remembers every lesson you finish.