Ruby: constants (Junior)
This course covers Ruby constants: names that start with an uppercase letter, decided when the code is parsed. It shows why reassigning a constant only prints a warning and why the object behind a constant can still change unless it is frozen. It explains the two lookup paths, lexical scoping through Module.nesting and the ancestor chain fallback. It then covers const_get, const_set and const_defined?, and how Zeitwerk autoloading creates namespace constants. The course ends with a challenge built on a frozen Hash constant.
What you'll learn
- ✓How Ruby recognizes a constant and the SCREAMING_SNAKE_CASE and CamelCase conventions
- ✓Why reassignment warns and how .freeze prevents mutation of Array, Hash and String constants
- ✓How lexical scoping searches Module.nesting to find a constant
- ✓How the ancestor chain acts as a fallback when lexical lookup finds nothing
- ✓Using const_get, const_set and const_defined? with names known only at runtime
- ✓How Zeitwerk auto-vivifies namespace modules and when a namespace file adds behavior
What makes a constant
This app's Auth::PasswordPolicy opens with three lines that decide how every password in the app is validated:
Read the full lesson free →Curriculum
7 lessonsWhat makes a constant
A name starting with an uppercase letter is a constant, and reassigning it prints a warning instead of raising.
Constants can still be mutated
Changing the object a constant points to gives no warning, so Array and Hash constants need .freeze.
Lexical scoping and constant lookup
Ruby searches the modules wrapping the code, shown by Module.nesting, and repeats that search on every call.
The ancestor chain fallback
When lexical lookup fails, Ruby checks the ancestor chain, and raises NameError if neither path finds the constant.
const_get, const_set, and reflection
const_get, const_set and const_defined? read, define and check constants whose names are held as strings or symbols.
Constants and Zeitwerk autoloading
Zeitwerk turns file paths into constants and creates empty namespace modules when no matching file exists.
Putting it together
A review of the course topics followed by a challenge that reads rates from a frozen Hash constant.