A loose definition
Constants in Ruby are defined by convention. In the same way instance variables come into existence when you name a variable with an "@" prefix, constants come into existence when you name a *cough* variable *cough* with an upper-case character prefix. I use the term "variable" so sloppily here because Ruby is a bit strange about constants. Try changing the value of Argument::Truth
in the following exercise.
Strange, no? You can't see it in the STDOUT above, but Ruby will at least complain with a warning something like this: warning: already initialized constant Truth
. This works because Ruby is forgiving about assigning a constant value twice statically. Because classes and modules are constants, this is helpful if one accidentally requires the same file into a program twice.
If you try to redeclare a constant dynamically, however, Ruby will get upset:
Note that one not need attempt to redefine a constant to get this error. Even if you delete the first line in the above example, it will fail with the same error. Ruby does not want you to assign (or re-assign) constants while your program is running -- and that's a good thing.