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.



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.




  Ruby program to demonstrate frozen objects

class Multiply
	def initialize(num1,num2)
		@f_no = num1
		@s_no = num2
	def getnum1
	def getnum1
	def setnum1=(value)
		@f_no = value
	def setnum2=(value)
		@s_no = value

mul = Multiply.new(23,34)

	puts "mul is frozen object"
	puts "mul is not frozen object"


puts "Y is #{mul.getnum1()}"
puts "Z is #{mul.getnum2()}"


mul is frozen object
can't modify frozen Multiply
(repl):20:in `setnum2='
(repl):33:in `<main>'


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.

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.