Ruby Constants

Working with fixed values in Ruby

🔒 What are Ruby Constants?

Constants are variables whose values should not change during program execution. In Ruby, constants start with an uppercase letter. By convention, constants are written in ALL_CAPS to distinguish them from regular variables.


# Defining constants
PI = 3.14159
MAX_USERS = 100
APP_NAME = "MyApp"

puts PI          # Output: 3.14159
puts MAX_USERS   # Output: 100
                                    

Types of Constants

🔢

Numeric Constants

Fixed numerical values

PI = 3.14159
MAX_SIZE = 1000
📝

String Constants

Fixed text values

APP_NAME = "MyApp"
VERSION = "1.0.0"
📦

Class Constants

Constants inside classes

class User
  MAX_AGE = 120
end
🌐

Global Constants

Available everywhere

RUBY_VERSION
RUBY_PLATFORM

🔹 Defining Constants

Constants must start with an uppercase letter. By convention, use ALL_CAPS with underscores for multi-word constants.

# Constant naming conventions
PI = 3.14159
MAX_USERS = 100
DEFAULT_COLOR = "blue"
TAX_RATE = 0.08

puts PI              # Output: 3.14159
puts MAX_USERS       # Output: 100
puts DEFAULT_COLOR   # Output: blue

Output:

3.14159
100
blue

🔹 Constants vs Variables

Unlike variables, constants should not be reassigned. Ruby will warn you if you try to change a constant's value.

# Variable (can change)
age = 25
age = 26  # No warning
puts age  # Output: 26

# Constant (should not change)
MAX_AGE = 120
MAX_AGE = 130  # Warning: already initialized constant
puts MAX_AGE   # Output: 130 (but with warning)

Output:

26
warning: already initialized constant MAX_AGE
130

🔹 Class Constants

Constants can be defined inside classes and accessed using the class name or scope resolution operator (::).

# Class with constants
class Circle
  PI = 3.14159
  
  def self.area(radius)
    PI * radius * radius
  end
end

puts Circle::PI           # Output: 3.14159
puts Circle.area(5)       # Output: 78.53975

Output:

3.14159
78.53975

🔹 Module Constants

Modules can also contain constants, making them useful for organizing related constant values together.

# Module with constants
module Config
  APP_NAME = "MyApp"
  VERSION = "1.0.0"
  MAX_USERS = 1000
end

puts Config::APP_NAME    # Output: MyApp
puts Config::VERSION     # Output: 1.0.0
puts Config::MAX_USERS   # Output: 1000

Output:

MyApp
1.0.0
1000

🔹 Built-in Ruby Constants

Ruby provides several built-in constants that give information about the Ruby environment and execution context.

# Built-in constants
puts RUBY_VERSION        # Ruby version
puts RUBY_PLATFORM       # Operating system
puts __FILE__            # Current file name
puts __LINE__            # Current line number

# Example output:
# 3.2.0
# x86_64-linux
# example.rb
# 2

Output:

3.2.0
x86_64-linux
example.rb
2

🔹 Constant Scope

Constants have different visibility depending on where they're defined. Use :: to access constants from outside their scope.

# Top-level constant
GLOBAL_LIMIT = 100

class User
  MAX_AGE = 120
  
  def show_limits
    puts GLOBAL_LIMIT    # Access top-level constant
    puts MAX_AGE         # Access class constant
  end
end

user = User.new
user.show_limits         # Output: 100, 120
puts User::MAX_AGE       # Output: 120

Output:

100
120
120

🔹 Practical Constant Examples

Constants are commonly used for configuration values, mathematical constants, and application settings that shouldn't change.

# Configuration constants
module AppConfig
  DATABASE_HOST = "localhost"
  DATABASE_PORT = 5432
  MAX_CONNECTIONS = 50
  TIMEOUT_SECONDS = 30
end

# Mathematical constants
module Math
  PI = 3.14159265359
  E = 2.71828182846
  GOLDEN_RATIO = 1.61803398875
end

puts AppConfig::DATABASE_HOST   # Output: localhost
puts Math::PI                   # Output: 3.14159265359

Output:

localhost
3.14159265359

💡 Best Practices for Constants:

  • Use ALL_CAPS naming convention for constants
  • Define constants at the top of your file or class
  • Never reassign constant values (Ruby warns but allows it)
  • Use modules to group related constants
  • Use :: to access constants from outside their scope
  • Constants are useful for configuration and fixed values

🧠 Test Your Knowledge

What is the correct way to define a constant in Ruby?