How to Freeze String in Ruby: Syntax and Examples
In Ruby, you can freeze a string by calling the
freeze method on it, which makes the string immutable. Alternatively, you can use the magic comment # frozen_string_literal: true at the top of your file to freeze all string literals automatically.Syntax
To freeze a string in Ruby, use the freeze method on a string object. This prevents any further modifications to that string.
You can also enable frozen string literals for the entire file by adding the magic comment # frozen_string_literal: true at the top. This makes all string literals immutable by default.
ruby
my_string = "hello" my_string.freeze # or enable frozen string literals for the whole file # frozen_string_literal: true another_string = "world"
Example
This example shows how freezing a string prevents changes and how the frozen string literal comment works.
ruby
# Using freeze method my_string = "hello" my_string.freeze begin my_string << " world" rescue => e puts e.message end # Using frozen string literal comment # frozen_string_literal: true another_string = "ruby" begin another_string << " rocks" rescue => e puts e.message end
Output
can't modify frozen String
can't modify frozen String
Common Pitfalls
A common mistake is trying to modify a frozen string, which raises a RuntimeError. Also, freezing a string does not affect copies or new strings created from it.
Remember that string literals are mutable by default unless you use the magic comment.
ruby
# Wrong way: modifying a frozen string str = "hello".freeze str << " world" # Raises error # Right way: duplicate before modifying str2 = str.dup str2 << " world" puts str2 # Outputs: hello world
Output
hello world
Quick Reference
| Action | Code Example | Effect |
|---|---|---|
| Freeze a string | "hello".freeze | Makes the string immutable |
| Enable frozen literals | # frozen_string_literal: true | Freezes all string literals in the file |
| Modify copy safely | str2 = str.dup | Creates a mutable copy to modify |
Key Takeaways
Use
freeze to make a string immutable and prevent changes.Add
# frozen_string_literal: true at the top of your file to freeze all string literals automatically.Modifying a frozen string raises a RuntimeError, so duplicate it first if you need a mutable copy.
Freezing strings can improve performance by avoiding unnecessary object copies.
Remember that freezing affects the string object itself, not other strings created from it.