Bird
Raised Fist0
Rubyprogramming~10 mins

Immutable data with freeze in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Immutable data with freeze
Create object
↓
Call freeze on object
↓
Object becomes immutable
↓
Attempt to modify object?
Yes→Error raised
No↓
Use object safely as immutable
This flow shows how freezing an object in Ruby makes it immutable, preventing any changes and raising errors if modification is attempted.
Execution Sample
Ruby
arr = [1, 2, 3]
arr.freeze
arr << 4
This code creates an array, freezes it to make it immutable, then tries to add an element, which causes an error.
Execution Table
StepActionObject StateResult/Output
1Create array arr = [1, 2, 3][1, 2, 3] (mutable)Array created
2Call arr.freeze[1, 2, 3] (frozen)Array is now immutable
3Attempt arr << 4[1, 2, 3] (frozen)FrozenError: can't modify frozen Array
💡 Execution stops because modifying a frozen object raises a FrozenError
Variable Tracker
VariableStartAfter freezeAfter modification attempt
arr[1, 2, 3] (mutable)[1, 2, 3] (frozen)[1, 2, 3] (frozen, unchanged)
Key Moments - 2 Insights
Why does arr << 4 cause an error after freeze?
Because after freeze (see step 2 in execution_table), the array becomes immutable and any modification like << raises a FrozenError.
Does freeze change the contents of the object?
No, freeze only prevents changes; the contents remain the same as shown in variable_tracker where arr stays [1, 2, 3].
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of arr after step 2?
AMutable array [1, 2, 3]
BFrozen array [1, 2, 3]
CEmpty array []
DArray with 4 elements
💡 Hint
Check the 'Object State' column at step 2 in execution_table
At which step does the program raise an error?
AStep 3
BStep 2
CStep 1
DNo error
💡 Hint
Look at the 'Result/Output' column in execution_table for error messages
If we remove arr.freeze, what would happen at step 3?
ARuntimeError raised
BArray remains unchanged
C4 is added to the array
DProgram crashes immediately
💡 Hint
Consider what freeze does by looking at variable_tracker and execution_table
Concept Snapshot
Ruby's freeze method makes an object immutable.
Once frozen, any attempt to modify it raises a FrozenError.
Freeze does not change the object's contents.
Use freeze to protect data from accidental changes.
Full Transcript
This example shows how to make data immutable in Ruby using freeze. First, an array is created with three numbers. Then, freeze is called on the array, which prevents any changes. When the code tries to add a new element to the frozen array, Ruby raises a FrozenError because the array is now immutable. The variable tracker shows that the array contents stay the same before and after freezing. This helps avoid bugs by protecting data from accidental modification.

Practice

(1/5)
1. What does the freeze method do to an object in Ruby?
easy
A. Prevents any further modifications to the object
B. Deletes the object from memory
C. Duplicates the object
D. Makes the object mutable

Solution

  1. Step 1: Understand the purpose of freeze

    The freeze method is used to make an object immutable, meaning it cannot be changed after freezing.
  2. Step 2: Identify the effect on the object

    Once frozen, any attempt to modify the object will raise an error, so it prevents further changes.
  3. Final Answer:

    Prevents any further modifications to the object -> Option A
  4. Quick Check:

    freeze makes object immutable = Prevents changes [OK]
Hint: Freeze means no changes allowed after calling it [OK]
Common Mistakes:
  • Thinking freeze deletes the object
  • Confusing freeze with duplication
  • Assuming freeze makes object mutable
2. Which of the following is the correct way to freeze a string name in Ruby?
easy
A. freeze(name)
B. name.frozen = true
C. name.freeze()
D. freeze name

Solution

  1. Step 1: Recall Ruby method call syntax

    In Ruby, to call a method on an object, use dot notation like object.method().
  2. Step 2: Identify the correct freeze syntax

    The correct way to freeze the string name is name.freeze(). Other options are invalid syntax or incorrect usage.
  3. Final Answer:

    name.freeze() -> Option C
  4. Quick Check:

    Method call with dot and parentheses = Correct freeze syntax [OK]
Hint: Use dot notation: object.freeze() to freeze [OK]
Common Mistakes:
  • Using freeze as a standalone function
  • Trying to assign frozen = true
  • Omitting dot before freeze
3. What will be the output of this Ruby code?
arr = [1, 2, 3]
arr.freeze
arr << 4
puts arr.inspect
medium
A. [1, 2, 3, 4]
B. RuntimeError: can't modify frozen Array
C. [1, 2, 3]
D. SyntaxError

Solution

  1. Step 1: Understand freezing the array

    The array arr is frozen using arr.freeze, making it immutable.
  2. Step 2: Analyze the modification attempt

    Trying to append 4 with arr << 4 will raise a RuntimeError because the array is frozen and cannot be changed.
  3. Final Answer:

    RuntimeError: can't modify frozen Array -> Option B
  4. Quick Check:

    Frozen object + modification = RuntimeError [OK]
Hint: Modifying frozen object causes RuntimeError [OK]
Common Mistakes:
  • Assuming frozen array can still be changed
  • Expecting silent failure or no error
  • Confusing output with syntax error
4. Identify the error in this Ruby code snippet:
str = "hello"
str.freeze
str[0] = 'H'
puts str
medium
A. RuntimeError: can't modify frozen String
B. SyntaxError due to invalid string modification
C. No error, output is "Hello"
D. Output is "hello" without changes

Solution

  1. Step 1: Recognize string freezing effect

    The string str is frozen, so it cannot be changed after str.freeze.
  2. Step 2: Understand the attempted modification

    Trying to change the first character with str[0] = 'H' raises a RuntimeError because the string is frozen.
  3. Final Answer:

    RuntimeError: can't modify frozen String -> Option A
  4. Quick Check:

    Frozen string + modification = RuntimeError [OK]
Hint: Frozen string cannot be changed, causes RuntimeError [OK]
Common Mistakes:
  • Thinking string changes silently fail
  • Expecting output "Hello" without error
  • Confusing syntax error with runtime error
5. Given this code, what is the best way to safely modify a frozen array without error?
original = [10, 20, 30].freeze
# Your code here to add 40
hard
A. original.freeze(false)
B. original << 40
C. original.push(40)
D. original = original.dup << 40

Solution

  1. Step 1: Understand frozen array cannot be changed

    The array original is frozen, so direct modification like << or push will cause errors.
  2. Step 2: Use duplication to create a modifiable copy

    Using original.dup creates a new unfrozen copy. Then appending 40 to this copy is allowed.
  3. Step 3: Assign the modified copy back

    Assigning the new array with 40 added back to original variable safely updates it without error.
  4. Final Answer:

    original = original.dup << 40 -> Option D
  5. Quick Check:

    Duplicate frozen object before modifying = Safe change [OK]
Hint: Duplicate frozen object before changing it [OK]
Common Mistakes:
  • Trying to modify frozen array directly
  • Using non-existent freeze(false) method
  • Assuming push works on frozen array
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard