Ruby - Introduction Constants


The unchanging values are called constants, and can be represented in Ruby by a variable name beginning with a capital letter:

Pi = 3.141592 

If you enter the preceding line and try to change the value of Pi, but you'll get a warning:


Pi = 3.141592 
Pi = 3.141592 
Pi = 500


Constants are objects whose values never change.

For example, PI in Ruby's Math module is a constant.

Constants in Ruby begin with a capital letter.

Class names are also constants. You can obtain a list of all defined constants using the constants method:


puts Object.constants


Ruby provides the const_get and const_set methods to get and set the value of named constants specified as symbols.

symbols identifiers are preceded by a colon such as :RUBY_VERSION.

Ruby's constants may be assigned new values:

RUBY_VERSION = "1.8.7" 
RUBY_VERSION = "2.5.6" 

The previous reassignment of the RUBY_VERSION constant produces an "already initialized constant" warning but not an error!

You can even reassign constants declared in Ruby's standard class library.

For example, here I reassign the value of PI.

Although this displays a warning, the assignment succeeds nonetheless:


puts Math::PI    #=> 3.141592653589793 
Math::PI = 100   #=> warning: already initialized constant PI 
puts Math::PI    #=> 100
#  www  .j av a 2s  .c o m