Constant References
A constant in Ruby is like a variable, except that its value is
supposed to remain constant for the duration of a 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.
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.
Although constants look like local variables with capital letters, they have the visibility of global variables: they can be used anywhere in a Ruby program without regard to scope. Unlike global variables, however, constants can be defined by classes and modules and can therefore have qualified names.
A constant reference is an expression that evaluates to the value of the named constant. The simplest constant references are primary expressions—they consist simply of the name of the constant:
CM_PER_INCH = 2.54 # Define a constant. CM_PER_INCH # Refer to the constant. Evaluates to 2.54.
In addition to simple references like this one, constant
references can also be compound expressions. In this case, :: is used to separate the name of the
constant from the class or module in which it is defined. The lefthand
side of the :: may be an arbitrary ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access