How to freeze constants in Ruby

Introduction

Just like in many programming languages Ruby has CONSTANTS, which its value cannot be changed. Right ? Well, it should be like that but in Ruby you can change the value of a constant and the only feedback you get about it, is a warning message telling you that the constant value was already initialized.

Ruby constants can change

Like I mentioned in the introduction, Ruby constants can change. Why does this happen ? Because in Ruby variables aren’t containers, they are just pointers to objects. This may sound weird if you come from a programming language like Java or any other that has constants.

Here’s an example of it:

MY_CONSTANT = 1

MY_CONSTANT = 2

MY_CONSTANT = 3

This is totally acceptable in Ruby, the result you get is:

Bildschirmfoto 2017-12-03 um 8.49.39 AM

If you don’t pay attention to these warnings you can get a lot of problems with it.

Is there any way to avoid it ? Well, the best you can do is to use an immutable object

Example:

MY_CONSTANT = “Here is an example”.freeze

And you will see this error:

Bildschirmfoto 2017-12-03 um 8.54.31 AM

Keep in mind you can still change what the MY_CONSTANT constant is pointing to, the only thing freeze protects you from is from changing the value of the object itself.

Acknowledgment

Thanks for reading this post, it is always a pleasure writing for you guys. If you like what you just read and somehow you want to support me, you can become a Patreon . Being my Patreon makes you get my private posts about programming with iOS and Ruby.

If you’d like to know more about me or what I do, you can follow me on Instagram or Twitter .

See you next time!

Advertisements