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
freezemethod will result in the program throwing a runtime error.
# using freeze with an array fruits = ["apple", "pear", "mango"] fruits.freeze fruits << "grapes"
Ruby objects, such as integers and floats, are all frozen by default and cannot be updated or modified.
freezemethod 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
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?
View all Courses