Ruby Constants


A Ruby constant is like a variable, except that its value is supposed to remain constant for the duration of the program. The Ruby interpreter does not actually enforce the constancy of constants, but it does issue a warning if a program changes the value of a constant (as shown in this trivial example) - p054constwarn.rb

Produces a warning:

Lexically, the names of constants look like the names of local variables, except that they begin with a capital letter. By convention, most constants are written in all uppercase with underscores to separate words, LIKE_THIS. Ruby class and module names are also constants, but they are conventionally written using initial capital letters and camel case, LikeThis.

Note that constants do not exist until a value is actually assigned to them.

Although constants should not be changed, you can modify the internal states of the objects they reference, as seen in p055constalter.rb

IN RAILS: You can find examples of this kind of operation (modify) in the Rails source code, where constants figure prominently and the objects they represent undergo fairly frequent changes.

Note:

  • Constants defined within a class or module may be accessed anywhere within the class or module.
  • Outside the class or module, they may be accessed using the scope operator, :: prefixed by an expression that returns the appropriate class or module.
  • Constants defined outside any class or module may be accessed as it is or by using the scope operator with no prefix.
  • Constants may not be defined in methods.
  • Constants may be added to existing classes and modules from the outside by using the class or module name and the scope operator before the constant name.

The program p056const.rb shows all of this:

Another elaborate example on own methods in a class is p057mymethods2.rb In this example we shall also see how to write a class method.

Summary

I have listed down all the important points you need to remember after you have completed the following topics: Object Serialization, Modules/Mixins, Self, Constants.

Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them. Much of the material on rubylearning.com and in the course at rubylearning.org is drawn primarily from the Programming Ruby book, available from The Pragmatic Bookshelf.