Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to freeze objects in Ruby

Hamza

The freeze method in Ruby is used to ensure that an object cannot be modified. This method is a great way to create immutable objects.

Any attempt to modify an object that has called the freeze method will result in the program throwing a runtime error.

# using freeze with an array
fruits = ["apple", "pear", "mango"]
fruits.freeze
fruits << "grapes"
These coding examples will throw a runtime error.

Ruby objects, such as integers and floats, are all frozen by default and cannot be updated or modified.

The freeze method has limitations

It is important to note that variables referencing frozen objects can be updated. This is because only the objects are frozen, not the variables that point to those objects.

The example below shows how a frozen object can be replaced by a new object that is accessible by the same variable:

str = "Hello World"
str.freeze
str = "This is a new string"
puts str # the program prints the variable without errors

Use frozen? to verify if an object is immutable.

str1 = "Hello World"
str1.freeze

str2 = "This a second string"

var = 20.5
var.freeze

puts 20.frozen?
puts str1.frozen?
puts str2.frozen?
puts var.frozen?

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring