๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

Ruby Frozen Objects

freeze locks an object so its contents stay as they are. Its frozen verdict reports whether an object is locked.

Verdicts before and after

The string starts unlocked, so the first frozen? line prints false. After freeze runs, the same line prints true.

title = "draft"
puts title.frozen?
title.freeze
puts title.frozen?

freeze returns the object itself

The value freeze returns is compared with the string that was frozen. The verdict is true, and the string reports itself frozen.

note = "memo"
returned = note.freeze
puts returned == note
puts note.frozen?

A frozen array still reads

Freezing the array locks it, but reads still work. Indexing and length answer as they did before the freeze.

numbers = [10, 20, 30]
numbers.freeze
puts numbers.frozen?
puts numbers[1]
puts numbers.length

dup drops the lock, clone keeps it

Both copies come from the same frozen string. The dup copy reports false from frozen?, and the clone copy reports true.

original = "locked"
original.freeze
copy_dup = original.dup
copy_clone = original.clone
puts copy_dup.frozen?
puts copy_clone.frozen?

Example

basket = ["apple", "pear"]
puts basket.frozen?
basket.freeze
puts basket.frozen?
puts basket.first
fresh = basket.dup
puts fresh.frozen?
fresh << "plum"
puts fresh.length
twin = basket.clone
puts twin.frozen?

Key points

  • frozen? answers false for a fresh object and true after freeze.
  • freeze returns the object itself, not a copy.
  • A frozen array still answers reads like indexing and length.
  • dup builds a copy of a frozen object without the lock.
  • clone builds a copy of a frozen object and keeps the lock.

In this example, the basket array freezes after the first verdict line. Reads still answer from the frozen basket, and dup gives an unlocked copy that grows to three items. clone gives a copy that stays frozen.

Note

freeze locks the one object it is called on.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does dup do with the frozen state of an object?