What is Frozen String in Ruby: Explanation and Examples
frozen string is a string object that cannot be changed after it is created. When a string is frozen, any attempt to modify it will cause an error, helping to prevent accidental changes and improve performance.How It Works
Imagine you have a note written on a piece of paper. If you freeze the note by putting it in a sealed plastic cover, you can read it but cannot change what is written. In Ruby, freezing a string works similarly: it locks the string so no changes can be made to it.
This is useful because it protects the string from accidental edits, especially when the string is shared in different parts of a program. Ruby marks the string as frozen, and if you try to change it, Ruby will raise an error to stop you.
Freezing strings can also help Ruby run faster by saving memory, since frozen strings can be reused safely without copying.
Example
This example shows how to freeze a string and what happens if you try to change it afterward.
str = "hello" str.freeze begin str << " world" rescue => e puts e.message end puts str
When to Use
Use frozen strings when you want to make sure a string stays the same throughout your program. This is helpful for constants, configuration values, or any string that should not be changed by mistake.
For example, if you have a greeting message used in many places, freezing it prevents accidental edits that could cause bugs. It also improves performance by reducing memory use when the same string is reused.
Key Points
- A frozen string cannot be changed after creation.
- Trying to modify a frozen string raises an error.
- Freezing strings helps prevent bugs and saves memory.
- You can freeze a string by calling
freezeon it.