Constants

From RubySpec

Jump to: navigation, search

Constants in Ruby are denoted by capital letters. Any variable that begins with a capital letter is automatically a constant. (The underscore character '_' is considered lowercase in Ruby, so a variable named _FOO, for example, is not a constant.

Constants are used for values that the developer will generally not expect to reassign. Values that are, well, constant.

In keeping with its dynamic nature however, Ruby does allow constants to be reassigned. Ruby will issue a warning when a constant is reassigned, indicating that this was not intended by the original user, but will give the constant the new value. (This can be important when loading different Ruby files that might redefine a constant.)


 > Const = 1
 => 1
 > Const = 2
 => warning: already initialized constant Const
 => 2


As should be expected, if a constant refers to an object, the properties and internal of the object may be changed without any warning.

Note that class and module names are constants. This is why they must always begin with capital letters: It's not a convention but a syntax rule in ruby.

Examples:

 E = 2.718281828459045 #Euler number


 circumference = 2*Math::PI*10 #Math::PI already defined in the Math module. Both Math and PI are constants.
Personal tools