Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
How to Freeze Objects in Ruby?
3.
Example
3.1.
Code
3.2.
Output
3.3.
Analysis
4.
Limitations
5.
Frequently Asked Questions
5.1.
What is an Object in Ruby?
5.2.
How to freeze objects in Ruby?
5.3.
How is a frozen object different from an ordinary object?
5.4.
What happens when you copy a frozen object?
5.5.
What are the limitations of the freeze method? 
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Freezing Objects in Ruby

Author Lucifer go
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

There are many times when a programmer spends a lot of time and effort getting the object properties and variables just right. It will be unfortunate if someone accidentally or intentionally changes the object's properties.

Perhaps an opaque object can be transmitted between two classes via a third-party object, ensuring that it arrives unchanged. Maybe you want to use an object as a hash key and ensure no one changes it while it's in use. Maybe something is corrupting one of your objects, and you want Ruby to throw an exception as soon as it happens.

Ruby provides a straightforward method to help with this. Any object in Ruby can be frozen by invoking Object#freeze.

How to Freeze Objects in Ruby?

Any object in Ruby can be frozen using the Object#freeze method. We can't change the instance variables of a frozen object, we can't connect singleton methods with it, and we can't add, delete, or edit the methods of a frozen class or module.

We may use the Object#frozen function to see if an object is frozen. If the object is frozen, it returns true; otherwise, it returns false. We may use the freeze method in an object to transform an object into a constant.

It's worth noting that a frozen object can't be unfrozen. The syntax for freezing and object is: - 

Object_Name.freeze.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example

Code

#class is defined
class Addition
# intializing values
def set_values(x, y)
@a, @b = x, y
end

# functions to access the variables
def get_A
@a
end
def get_B
@b
end

# functions to set the variables
def set_A=(value)
@a = value
end
def set_B=(value)
@b = value
end
end

# new object created
sum = Addition.new(10, 20)

# the below line of code freezes the object
sum.freeze
if( sum.frozen? )
puts "Object is Frozen."
else
puts "Object is Not Frozen."
end

# using setter functions
sum.set_A = 30
sum.set_B = 50

# using accessor functions
sum.get_A()
sum.get_B()

puts "A is: #{sum.get_A()}"
puts "B is: #{sum.get_B()}"

Output

Object is Frozen

Runtime Error : prog.rb:18:in `set_A=': can't modify frozen Addition (RuntimeError)

from prog.rb:37:in `<main>'

Analysis

We used the sum.freeze method, due to which the object is now frozen, and we can't change the value of its method. Here, sum.frozen? The method is used to show whether the object is frozen or not.

Limitations

Variables referencing frozen objects can be updated, which is important to remember. This is due to the fact that only the objects themselves are frozen, not the variables that refer to them.

The following example demonstrates how a frozen item may be replaced with a fresh object that shares the same variable:

str = "Hi"
str.freeze
str = "New_Hi"
puts str 
# the program prints the variable without showing any errors

Frequently Asked Questions

What is an Object in Ruby?

The default root of all Ruby objects is an object. An object is a descendant of BasicObject, allowing for the creation of alternative object hierarchies. Object methods are available to all classes unless they are expressly overridden.

The Kernel module contains object mixes that make the built-in kernel functions globally available. You don't need to use the complete namespace when addressing constants in classes that inherit from the object. Referencing File inside YourClass, for example, will return the top-level File class.

The argument symbol in the descriptions of the object's methods refers to a symbol, which can be either a quoted-string or a Symbol.

How to freeze objects in Ruby?

The freeze method ensures that an object cannot be modified in Ruby. This method creates immutable objects such that any attempt to modify an object called the freeze method will result in the program throwing a runtime error.

How is a frozen object different from an ordinary object?

Unlike a normal object of a class,  we cannot change the instance variables of a frozen object, we can't connect singleton methods with it, and we can't add, delete, or edit the methods of a frozen class or module.

What happens when you copy a frozen object?

This depends on the method that is being used. For example, if you call an object's clone method, the entire object state (whether it is frozen) is copied to the new object. On the other hand, dup typically copies only the object's contents where the new copy will not inherit the frozen status.

What are the limitations of the freeze method? 

Variables referencing frozen objects can be updated, which is an important point to remember. This is due to the fact that only the objects themselves are frozen, not the variables that refer to them. Therefore the same variable name can be used again to refer to some other value.

Conclusion

In this article, we have extensively discussed Conditional Random Fields, their implementation, and their importance.

After reading about the Architecture of IoT, are you not feeling excited to read/explore more articles on the topic of Programming in IoT and learning Ruby? Don't worry; Coding Ninjas has you covered. To learn, see more blogs on RubyRuby Documentation, and Programming Language for IoT.
Check out this problem - Subarray Sum Divisible By K


Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Previous article
Object Marshalling in Ruby
Next article
Tainting Objects in Ruby
Live masterclass