How to Use the Freeze Method in Ruby

Hassan Ejaz Feb 15, 2024
How to Use the Freeze Method in Ruby

This article will introduce how we can use the freeze method to objects in Ruby.

Use the freeze Method in Ruby

We can use the freeze method in Ruby when we do not want to alter an object anymore, and we want to make sure that it cannot be amended. We can quickly generate immutable objects by using this method.

The program will show an error if we try to alter an object on which the freeze method is applied. A case of using the freeze method with an array is shown below.

# Ruby

fruits = %w[orange banana strawberry]

fruits.freeze

fruits << 'watermelon'

We will get an error when we try to run this code. In the case of a string, the usage of the freeze method is shown below.

# Ruby

str = 'Hey'

str.freeze

str << ' How are you?'

This will also show runtime errors. In the case of an object, the usage of the freeze method is shown below.

# Ruby

class Fruits
  def initialize(name)
    @name = name
  end

  def get_name
    @name
  end

  def set_name(name)
    @name = name
  end
end

a = Fruits.new('apple')

a.freeze
a.set_name('melon')
puts a.get_name

Output:

freeze method in Ruby

In the above examples, an error occurred because we had tried to alter objects when they were already frozen by the freeze method.

Limitations of the freeze Method in Ruby

There are some limitations to the freeze method. It is essential to understand that we can modify variables related to frozen objects.

This is because we have only frozen the objects by using this method. Variables that are related to those objects are free to be altered.

Here is an example illustrating how we can change a frozen object to a new thing by accessing the same variable.

# Ruby

str = 'Hey James'
str.freeze

str = 'Hey Petr'

puts str

Output:

limitations of freeze method in Ruby

We can use the freeze method to check if an object is immutable.

# Ruby

str2 = 'Hey Julia'

str2.freeze

str4 = 'Julia is very nice'

num = 120.5

num.freeze

Related Article - Ruby Method