How to freeze constants in Ruby


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:




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


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.


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!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s