Constants in Ruby
Constants are names starting with an uppercase letter. Reassigning a constant emits a warning (not an error) to discourage changes.
Basics
Use constants for configuration and fixed values. They are looked up lexically.
PI = 3.14159
PI = 3.14 # warning: already initialized constant PI
Namespacing
Organize constants under modules/classes for clarity; access with the :: operator.
module App
VERSION = "1.0.0"
class Config
DEFAULTS = { debug: false }
end
end
App::VERSION
App::Config::DEFAULTS
Lookup and reflection
Constant lookup prefers lexical scope, then ancestors. Reflect with helpers.
Module.nesting # current lexical nesting
Object.const_defined?(:PI)
Object.const_get(:PI)
Immutability of referenced objects
Constants reference objects, which can still be mutable. Freeze objects to prevent accidental changes.
TOKEN = "abc".freeze # freeze object to avoid mutation
SET = [1,2,3].freeze
Style notes
- Use
SCREAMING_SNAKE_CASEfor global constants,CamelCasefor classes/modules - Group related constants inside modules/classes for discoverability
Summary
- Uppercase names define constants; reassignment emits a warning
- Lexical lookup first, then ancestors; use reflection when needed
- Freeze referenced objects if you want true immutability