Constants (should) have the same value during execution of the program.
Its like a variable, except a Ruby constant should not change its value.

This is very useful for certain types of data that never change. Think of a value like Pi or the version of the program.

If you try to change the value of a constant, the Ruby interpreter will throw an warning. Ruby is however not strict, it will change the value anyway.

Download Free Ruby Ebook

Constants in ruby

Example

You can create a constant by adding _CONST to the name. In Ruby, the value of a constant can be changed but it will show a warning.

1
2
3
4
5
#!/usr/bin/ruby

A_CONST = 3
A_CONST = A_CONST + 1
print(A_CONST)

This wil show the warning:

1
2
test.rb:3: warning: already initialized constant A_CONST
test.rb:2: warning: previous definition of A_CONST was here

But the actual value is changed. In other programming languages constants are more strict, its value cannot be changed.

Unless a value is actually assigned to them, constants do not exist.

Constants cannot be defined inside methods. But they can be defined throughout the program or inside classes.

Constants inside classes

To access constants inside classes, you can use the :: operator.

The simple example below deomnstrates how to use a constant defined in a class.

1
2
3
4
class Example
A_CONST = 3
end
puts Example::A_CONST

This will output the value of the constant.