How to freeze objects in Ruby?

RubyServer Side ProgrammingProgramming

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.


The syntax to freeze an object is shown below.


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 << "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.


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

   # accessor methods
   def getA

   def getB

   # setter methods
   def setA=(value)
      @first = value

   def setB=(value)
      @second = value

# create an object
add =, 20)

# let us freez this object
if( add.frozen? )
   puts "Frozen object"
   puts "Normal object"

# now try using setter methods
sub.setA = 30
sub.setB = 50

# use accessor methods

puts "First is : #{sub.getA()}"
puts "Second is : #{sub.getB()}"


Frozen object
main.rb:37:in `<main>': undefined local variable or method `sub' for main:Object (NameError)
Updated on 25-Jan-2022 11:31:28