Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I change constants?

Tags:

ruby

class TestClass
  CONSTANT = 1
end

TestClass::CONSTANT = 2

Apparently you can change value of the constant in Ruby any time. Why are they even called "constants" if you can change them?

What is the purpose of these 'constants'? How does the ability to change their value make programming easier?

like image 680
Sergey Avatar asked Jan 17 '12 12:01

Sergey


1 Answers

Well, constants in Ruby are relatively variable. Objects they point to can be swapped (as in your example) and their state can be changed as well.

class TestClass
  Constant = []
end
TestClass::Constant << "no warning at all!"

The only advantage they provide are warnings generated when you make an existing constant point to another object. See "Programming Ruby", section "Variables and Constants". It's old but still valid.

The purpose for Ruby's constants to exist is signalling that a given reference shouldn't be changed. For instance, if you do Math::PI = 3.0 you deserve to be warned.

Theoretically, you could break compatibility with the original implementation and enforce constants' immutability. As a result you could achieve a slight performance improvement thanks to optimised method dispatching.

In the example above you'd know that Constant.is_a? Array so dispatching the << symbol to the actual method could be done only once, on the first execution of that line. The problem is that Ruby enables you to redefine Array#<< thus making the problem more tricky.

Checking whether various Ruby implementations try to use such optimisation would require some additional research and digging in their documentation or sources.

like image 111
Jan Avatar answered Sep 26 '22 16:09

Jan