How to Use the freeze Method in Ruby



In this article, you will learn how to use the freeze method in Ruby.

The freeze Method

In Ruby, the freeze method is used to prevent modifications to an object. Once an object is frozen, its state cannot be changed. This is useful when you want to ensure that an object remains constant and cannot be altered accidentally or intentionally. Here’s how you can use the freeze method in Ruby:

Freeze an object

To freeze an object, simply call the freeze method on it:

str = "hello"

In this example, the str object is frozen, and any attempt to modify it will result in an error.

Check if an object is frozen

You can check whether an object is frozen using the frozen? method:

str = "hello"
str.frozen? #=> true

In this example, the frozen? method returns true because the str object is frozen.

Modify a frozen object

If you attempt to modify a frozen object, Ruby will raise a FrozenError exception:

str = "hello"
str.upcase! #=> FrozenError: can't modify frozen String

In this example, the upcase! method is called on the frozen str object, which raises a FrozenError exception because the object is frozen and cannot be modified.

Freeze all objects in a nested structure

If you have a nested data structure (such as an array or a hash) and you want to freeze all the objects inside it, you can use the freeze method recursively:

hash = {a: [1, 2], b: {c: 3}}

In this example, the hash object and all its nested objects are frozen, ensuring that the entire data structure remains constant and cannot be modified.