liveBook · Manning

Immutable collection

As explained in The Well-Grounded Rubyist, Fourth Edition

Immutability is the property of data or objects that prevents their state from being changed after creation.

An immutable value cannot be changed after creation. Ruby symbols are immutable by nature; most other Ruby objects can be changed unless they are frozen. section 8.2.1 section 16.2.1

Calling `freeze` prevents changes to that object, and `frozen?` checks its status. Freezing an object does not guarantee that all of its attributes are immutable, so do not assume nested state is protected. section 16.2.1

>> the_unseen = Record.new("Quasimoto", "The Unseen", 2000, 3.5)
>> the_unseen.rating = 4.5
=> 4.5
>> the_unseen.freeze
>> the_unseen.rating.frozen?
=> true
>> the_unseen.artist = "Madlib"
=>  can't modify frozen #<Class:#<Record:0x0000000131dbfa60>>: 
➥#<Record:0x0000000131dbfa60 @artist="Quasimoto", @title="The Unseen", 
➥@year=2000, @rating=4.5> (FrozenError)

The Record example shows a mutable object before freezing and a rejected attribute assignment afterward. section 16.2

Frozen string literals offer a practical case: duplicate literals can share an object, while `dup`, `String.new`, or unary `+` can provide a mutable string. Frozen behavior is not absolute, and frozen-string support may vary across Ruby releases. section 16.2.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains symbol immutability, Ruby freezing, and frozen strings, while warning that freezing does not guarantee all attributes are immutable.
Examples
Uses symbols, a frozen Record instance, a mutable string constant, and frozen string literals with mutable copies.
What you can do after
Operate on Ruby objects with `freeze` and `frozen?`, and create mutable string copies with `dup`, `String.new`, or unary `+`.
How it connects
Connects immutability with functional programming, symbols, strings, and thread safety.

Also explained in

Compare how 24 books explain immutable collection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.