Prev - DUP - Next - TOC

Class constants


The next topic is class constants. A constant is specified by a capitalized name, and is defined by a substitution. An access of an undefined constant or a substitution to a defined constant causes an error.

 ruby> FOO
 ERR: Uninitialized constant FOO
 ruby> FOO = 5
 5
 ruby> FOO
 5
 ruby> FOO = 5
 ERR: already initialized constnant FOO

Constants are referred in a class/module scope. In other words, one can refer to a constant of the class (even of the parent class or the included module) or module definition.

 ruby> module ConstTest
 ruby|   CONST1 = 1
 ruby|   CONST2 = 3
 ruby|   CONST3 = 5
 ruby|   print CONST1, CONST2, CONST3, "\n"
 ruby|   def const_test
 ruby|     print CONST3, CONST2, CONST1, "\n"
 ruby|   end
 ruby| end
 135
 nil
 ruby> include ConstTest # makes consts be referred
 Object
 ruby> CONST1
 1
 ruby> CONST1 = 9  # can redefine consts of the ancestor (but should not)
 9
 ruby> const_test  # the above didn't affect to the ancestor's
 531

One can refer to constants of a class via the `::' operator.

 ruby> ConstTest::CONST1
 1

But a substitution with `::' is not allowed.

 ruby> ConstTest::CONST1 = 7
 ERR: compile error in eval():
 eval.rb:33: parse error
 ConstTest::CONST1 = 7
                   ^

Also, the `::' operator is available for a constant which is defined in the class or module; In the above, the constants CONST1, CONST2 and CONST3 can be refered to with `::' for the ConstTest module, but one can not refer CONST2 or CONST3 of an object of the class which include the ConstTest module (however CONST1 can be referred, as it is redefined in the class).


Prev - DUP - Next - TOC