Basics

Ruby Constants

Using Constants

Ruby constants use uppercase for semi-immutable values.

What Are Ruby Constants?

In Ruby, constants are used to store values that should not change throughout the execution of a program. By convention, constant names are written in uppercase letters. Although they can be reassigned, doing so will generate a warning. This makes them semi-immutable—encouraging developers to keep their values unchanged.

Declaring Constants in Ruby

Constants in Ruby are declared by assigning a value to an identifier that begins with an uppercase letter. It's a simple and straightforward process. Here's how you can declare a constant:

Accessing and Using Constants

Once you declare a constant, you can access its value just like any other variable. Constants are often used for values that are widely used across a program, such as configuration settings or fixed values. Consider the following example:

Reassigning Constants

Although Ruby allows reassignment of constants, this practice is discouraged. Assigning a new value to an existing constant generates a warning to alert the developer. This behavior ensures that the integrity of constant values is maintained unless absolutely necessary.

Constants and Scope

Constants have lexical scope. This means they are accessible within the context they are defined and any child contexts. However, if you define a constant within a class or module, it will not be directly accessible outside of it unless explicitly referenced.

Previous
Data Types