0
0
Rubyprogramming~10 mins

String freezing for immutability in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - String freezing for immutability
Create String object
Freeze String with .freeze
Attempt to modify String
Error raised: can't modify frozen String
String remains unchanged
This flow shows creating a string, freezing it to make it immutable, and what happens when you try to change it.
Execution Sample
Ruby
str = "hello"
str.freeze
str << " world"
Creates a string, freezes it, then tries to add more text, which causes an error.
Execution Table
StepActionString ValueFrozen?Result/Output
1Create string str = "hello""hello"falseString created, not frozen
2Call str.freeze"hello"trueString is now frozen (immutable)
3Attempt str << " world""hello"trueError: can't modify frozen String
💡 Modification attempt on frozen string raises error, stopping execution
Variable Tracker
VariableStartAfter freezeAfter modification attempt
str"hello""hello" (frozen)"hello" (frozen, unchanged)
Key Moments - 2 Insights
Why does str << " world" cause an error after freezing?
Because after step 2 in the execution_table, str is frozen and cannot be changed. Trying to add text raises an error.
Does freezing the string change its content immediately?
No, freezing only prevents future changes. The string content stays the same as shown in step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of str after step 2?
A"hello" (frozen)
B"hello world"
Cnil
D"hello" (not frozen)
💡 Hint
Check the 'String Value' and 'Frozen?' columns at step 2 in execution_table
At which step does the program raise an error?
AStep 2
BStep 3
CStep 1
DNo error
💡 Hint
Look at the 'Result/Output' column in execution_table for the error message
If we remove str.freeze, what would happen at step 3?
AError still occurs
BString becomes nil
CString changes to "hello world"
DProgram crashes before step 3
💡 Hint
Refer to variable_tracker and understand freezing prevents modification
Concept Snapshot
str = "text" creates a string
str.freeze makes it immutable
Trying to change frozen string causes error
Freezing does not change content
Use freeze to protect strings from accidental changes
Full Transcript
This example shows how to make a string unchangeable in Ruby using freeze. First, a string str is created with value "hello". Then str.freeze is called, which marks the string as frozen. After freezing, any attempt to modify str, like adding more text with <<, causes an error. The string content stays the same after freezing, but it cannot be changed anymore. This helps prevent bugs from accidental string changes.