Home »
Ruby Tutorial
Frozen objects in Ruby
By IncludeHelp Last updated : November 16, 2024
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?
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?
Example
=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 getnum2
@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 a frozen object"
else
puts "mul is not a frozen object"
end
# These lines will raise an error because the object is frozen
mul.setnum2 = 12
mul.setnum1 = 13
puts "Num1 is #{mul.getnum1}"
puts "Num2 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.
Another Example: Working with Frozen Objects
# Ruby program to demonstrate frozen objects
# Define a class with attributes and methods
class Example
attr_accessor :name, :value
def initialize(name, value)
@name = name
@value = value
end
end
# Create an instance of the class
obj = Example.new("Sample", 100)
# Freeze the object
obj.freeze
# Check if the object is frozen
if obj.frozen?
puts "The object is frozen!"
else
puts "The object is not frozen."
end
# Attempt to modify the frozen object
begin
obj.name = "NewName" # This will raise a runtime error
rescue => e
puts "Error: #{e.message}"
end
# Accessing values still works
puts "Name: #{obj.name}, Value: #{obj.value}"
Output
The object is frozen!
Error: can't modify frozen Example: #<Example:0x0000645aa8649058 @name="Sample", @value=100>
Name: Sample, Value: 100