Concept Flow - Frozen objects
Create object
Freeze object
Try to modify object?
Yes→Error: can't modify frozen object
No
Use object as is
End
An object is created and then frozen to prevent changes. Any attempt to modify it causes an error.
str = "hello" str.freeze str << " world"
| Step | Action | Object State | Result/Output |
|---|---|---|---|
| 1 | Create string str = "hello" | str = "hello" (not frozen) | No output |
| 2 | Call str.freeze | str = "hello" (frozen) | No output |
| 3 | Try str << " world" | str frozen | Error: can't modify frozen String |
| Variable | Start | After freeze | After modification attempt |
|---|---|---|---|
| str | "hello" (not frozen) | "hello" (frozen) | "hello" (frozen, unchanged) |
In Ruby, calling freeze on an object makes it immutable. Any attempt to change a frozen object raises an error. Use freeze to protect objects from accidental modification. Frozen objects keep their content but cannot be altered. Trying to modify frozen objects stops the program with an error.
freeze method do to an object in Ruby?freezefreeze method is used to make an object immutable, meaning it cannot be changed after freezing.str in Ruby?object.method.freeze on it: str.freeze(). The other options are invalid syntax.arr = [1, 2, 3] arr.freeze arr << 4 puts arr.inspect
arr is frozen with arr.freeze, so it cannot be changed.arr << 4, which modifies the array. Since it's frozen, this raises a runtime error.name = "Alice" name.freeze name[0] = 'M' puts name
name is frozen, so it cannot be changed after name.freeze.name[0] = 'M' modifies the string, which is forbidden and raises a runtime error.hash = {a: [1, 2], b: [3, 4]}
hash.freeze
hash[:a] << 5
puts hash[:a].inspect
What does this tell us about freezing objects?:a is an array, which is not frozen. Modifying this array with << 5 is allowed.Pass the test and this pattern moves unknown