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 arrayfruits = ["apple", "pear", "mango"]fruits.freezefruits << "grapes"
Ruby objects, such as integers and floats, are all frozen by default and cannot be updated or modified.
freeze
method has limitationsIt 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.freezestr = "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.freezestr2 = "This a second string"var = 20.5var.freezeputs 20.frozen?puts str1.frozen?puts str2.frozen?puts var.frozen?