Freezing Objects | Ruby

Any object can be frozen by invoking Object#freeze. A frozen object can not be modified: we can’t change its instance variables, we can’t associate singleton methods with it, and, if it is a class or module, we can’t add, delete, or modify its methods.
To test if an object is frozen we can use Object#frozen. It returns true in case the object is frozen, otherwise, return false value. The freeze method in object allows us to turning an object into a constant.

Note that a frozen object can’t be unfreeze.

Syntax: ObjectName.freeze

Below is the example to better understand:
Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program of freezing object
  
# define a class
class Addition
   # constructor method
   def initialize(x, y)
      @a, @b = x, y
   end
  
   # accessor methods
   def getA
      @a
   end
   def getB
      @b
   end
  
   # setter methods
   def setA=(value)
      @a = value
   end
   def setB=(value)
      @b = value
   end
end
  
# create an object
add = Addition.new(10, 20)
  
# let us freez this object
add.freeze
if( add.frozen? )
   puts "Addition object is frozen object"
else
   puts "Addition object is normal object"
end
  
# now try using setter methods
add.setA = 30
add.setB = 50
  
# use accessor methods
add.getA()
add.getB()
  
puts "A is : #{add.getA()}"
puts "B is : #{add.getB()}"

chevron_right


Output :

Addition object is frozen object
main.rb:20:in `setA=’: can’t modify frozen Addition (RuntimeError)
from main.rb:39:in `

In above example, a class Addition is created then we create an object name is add. by using add.freeze method the object is freeze now we can’t change the value of it’s method. Here, add.frozen? method is used to show object is freeze or not.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.