Home »
Ruby programming
Frozen objects in Ruby
Ruby | Frozen objects: In this tutorial, we are going to learn about the frozen objects in Ruby programming language with examples.
Submitted by Hrithik Chandra Prasad, on April 09, 2020
Ruby | Frozen objects
Freezing objects or instances in Ruby means that we are disallowing them to get modified in the future. You can understand this in a way that you can’t change their instance variables, you can’t provide singleton methods to it as well as if we are freezing a class or a module, and you can’t add, remove and bring some changes in its methods.
How to freeze objects in Ruby?
You can freeze objects in Ruby by in invoking freeze method which is a method defined in Object Class in Ruby's library. There is no method to unfreeze the object which is once frozen.
Syntax:
Object_name.freeze
How to check whether the object is frozen or not?
There is a very simple way to check whether the object is frozen or not. You only have to invoke frozen? method of Object class. If the method returns true then the object is frozen otherwise not.
Syntax:
Object_name.frozen?
Program:
=begin
Ruby program to demonstrate frozen objects
=end
class Multiply
def initialize(num1,num2)
@f_no = num1
@s_no = num2
end
def getnum1
@f_no
end
def getnum1
@s_no
end
def setnum1=(value)
@f_no = value
end
def setnum2=(value)
@s_no = value
end
end
mul = Multiply.new(23,34)
mul.freeze
if(mul.frozen?)
puts "mul is frozen object"
else
puts "mul is not frozen object"
end
mul.setnum2=12
mul.setnum1=13
puts "Y is #{mul.getnum1()}"
puts "Z is #{mul.getnum2()}"
Output
mul is frozen object
can't modify frozen Multiply
(repl):20:in `setnum2='
(repl):33:in `<main>'
Explanation:
In the above code, you can observe that we have frozen the object mul with the help of Object.freeze method. We are getting an error known as FrozenError because we are trying to bring changes in the variables of the frozen object with the help of some other methods. We know that we can’t bring any change in the variables of the object which is frozen.