Ruby FrozenError
An attempt to append to a frozen route raises FrozenError. A duplicate can hold the draft.
A simple example
FrozenError
- Start with An immutable list containing A
- Do this Add B to a new copy
- Result New list A, B
Syntax
rescue FrozenError
Run these examples in Ruby
Save one example at a time as lesson.rb. Use Ruby 2.6 or later.
ruby lesson.rbAdd a stop to a published bus route
A planner starts with a published route that riders can already see. She needs to add the museum to a draft while keeping the original schedule available to other passengers.
published = ["Station"].freeze
begin
published << "Museum"
rescue FrozenError
draft = published.dup << "Museum"
puts "[#{draft.join(', ')}]"
end
[Station, Museum]
The draft has two stops while the published route still has just the station.
Extend a draft shortlist
The school office is editing a mutable rehearsal list. Attempt to append one name to the roster. A published read-only list requires a working copy.
Protect a published result
A teacher opens an unmodifiable snapshot of the final roster. Attempt to append one name to the roster. A published read-only list requires a working copy.
What to watch for
Freezing an array only freezes the array itself, so consider whether nested objects may also change.