0
0
Rubyprogramming~5 mins

String freezing for immutability in Ruby

Choose your learning style9 modes available
Introduction

Freezing a string stops it from being changed. This helps keep data safe and avoids mistakes.

When you want to keep a string value the same throughout your program.
When sharing a string between parts of a program and want to prevent accidental changes.
When using strings as keys or constants that should not be modified.
When you want to improve performance by avoiding duplicate string objects.
Syntax
Ruby
string.freeze

Calling freeze on a string makes it immutable (unchangeable).

Trying to change a frozen string will cause an error.

Examples
This freezes the string stored in name.
Ruby
name = "hello"
name.freeze
This freezes the string literal "world" directly.
Ruby
"world".freeze
Check if a string is frozen using frozen? before and after freezing.
Ruby
greeting = "hi"
puts greeting.frozen?
# Output: false
greeting.freeze
puts greeting.frozen?
# Output: true
Sample Program

This program shows how freezing a string works and what happens if you try to change it after freezing.

Ruby
greeting = "hello"
puts greeting.frozen?  # false

greeting.freeze
puts greeting.frozen?  # true

# Trying to change frozen string causes error
begin
  greeting << " world"
rescue => e
  puts e.message
end
OutputSuccess
Important Notes

Freezing strings is useful to avoid bugs caused by accidental changes.

Frozen strings can improve memory usage by reusing the same object.

In Ruby 3.0+, you can use the magic comment # frozen_string_literal: true to freeze all string literals in a file.

Summary

Freezing a string makes it unchangeable.

Trying to modify a frozen string causes an error.

Use freezing to protect important string data and improve performance.