What is freeze in Ruby: Explanation and Examples
freeze is a method that makes an object immutable, meaning you cannot change it after freezing. Once an object is frozen, any attempt to modify it will raise a FrozenError.How It Works
Think of freezing an object like putting it in a locked box. Once inside, you can't change anything about it. In Ruby, calling freeze on an object locks it so that no further changes can be made to it.
This is useful because it prevents accidental changes to important data. For example, if you have a string or array that should stay the same throughout your program, freezing it ensures it stays constant.
Under the hood, Ruby marks the object as frozen. If you try to modify it later, Ruby will stop you by raising an error, protecting the object's state.
Example
This example shows how freezing a string prevents it from being changed:
name = "Alice" name.freeze begin name << " Smith" rescue => e puts e.message end
When to Use
Use freeze when you want to protect data from being changed accidentally. This is common when you have constants or configuration data that should remain the same.
For example, freezing strings used as keys in hashes or freezing arrays of settings helps avoid bugs caused by unexpected modifications.
It also improves program safety by making your intentions clear: this object is meant to stay unchanged.
Key Points
- freeze makes an object immutable.
- Trying to change a frozen object raises a
FrozenError. - Useful for protecting constants and important data.
- Works on most Ruby objects like strings, arrays, and hashes.