0
0
RubyConceptBeginner · 3 min read

What is Frozen String in Ruby: Explanation and Examples

In Ruby, a 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.

ruby
str = "hello"
str.freeze

begin
  str << " world"
rescue => e
  puts e.message
end

puts str
Output
can't modify frozen String hello
🎯

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 freeze on it.

Key Takeaways

A frozen string in Ruby is immutable and cannot be changed after freezing.
Modifying a frozen string causes a runtime error to protect data integrity.
Freezing strings is useful for constants and shared values to avoid bugs.
It can improve performance by allowing safe reuse of the same string object.