Junior Track Roadmap

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
Free preview · Lesson 1 4 min read

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 lessons
Type to start searching...