Library contents

Ruby FrozenError

An attempt to append to a frozen route raises FrozenError. A duplicate can hold the draft.

A simple example

FrozenError

  1. Start with An immutable list containing A
  2. Do this Add B to a new copy
  3. Result New list A, B
Creating a new collection keeps the original list intact.

Syntax

Ruby 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.rb

Add 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.

From the programpublished = ["Station"].freeze
Result[Station, Museum]
lesson.rb
published = ["Station"].freeze
begin
  published << "Museum"
rescue FrozenError
  draft = published.dup << "Museum"
  puts "[#{draft.join(', ')}]"
end
Output
[Station, Museum]

The draft has two stops while the published route still has just the station.

Advertisements

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.

GivenEditable list [Ada]
Worked resultName added

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.

GivenUnmodifiable list [Ada]
Worked resultMake a working copy

What to watch for

Freezing an array only freezes the array itself, so consider whether nested objects may also change.

Documentation for FrozenError