
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Freeze Objects in Ruby
Sometimes a situation arises where we would want to freeze the object instance so that it cannot be instantiated or modified and in Ruby, we can do that with the help of the freeze keyword.
The approach is to invoke the Object#freeze statement.
When we freeze an object, we are basically turning it into a constant and it should be noted that once an object is frozen, cannot be unfrozen.
Syntax
The syntax to freeze an object is shown below.
Object.freeze
Now that we know a little about freeze, let's take a couple of example to understand how it works.
Example 1
Consider the code shown below
veggies = ["spinach", "cucumber", "potato"] veggies.freeze veggies << "cauliflower"
In the above code, there's an array named veggies which contains three strings, and then on the next line, I invoked the freeze method on it and then lastly, I tried adding another string to the array.
Output
main.rb:3:in `<main>': can't modify frozen Array (RuntimeError)
Example 2
Let's consider a slightly more complex example where we would make use of getters and setters and then set one of the methods as frozen. Consider the code shown below.
# Freezing object example # define a class class Subtract # constructor method def initialize(x, y) @first, @second = x, y end # accessor methods def getA @first end def getB @second end # setter methods def setA=(value) @first = value end def setB=(value) @second = value end end # create an object add = Subtract.new(10, 20) # let us freez this object add.freeze if( add.frozen? ) puts "Frozen object" else puts "Normal object" end # now try using setter methods sub.setA = 30 sub.setB = 50 # use accessor methods sub.getA() sub.getB() puts "First is : #{sub.getA()}" puts "Second is : #{sub.getB()}"
Output
Frozen object main.rb:37:in `<main>': undefined local variable or method `sub' for main:Object (NameError)