Ruby idioms: safe navigation
This course explains how Ruby's safe navigation operator &. works. It compares &. chains with && chains and shows that &. evaluates each link once, returning nil for the whole chain when any link is nil. It covers arguments, blocks and operator methods, and what plain . does on nil. It pairs &. with || for default values. It explains when &. hides a bug instead of preventing one. It closes by reviewing real lines from the app's own code.
What you'll learn
- ✓How &. chains differ from && chains in evaluation and short-circuiting
- ✓Using &. with arguments, blocks and operator methods such as >
- ✓Why plain . raises NoMethodError on nil and what check &. adds
- ✓Combining &. with || for defaults, and the false value trap
- ✓Telling legitimately optional values apart from nil values that signal a bug
- ✓Reading real uses of &. in an application's code
Recap: the one line you've already seen
The lesson "The AND operator", in Logic: boolean algebra, taught && and its short-circuit behavior with this example:
Read the full lesson free →Curriculum
7 lessonsRecap: the one line you've already seen
Compares && and &. chains, showing that a nil at any depth makes the whole &. chain return nil.
Safe navigation with arguments and blocks
Shows that &. passes arguments and blocks through unchanged and also works in front of operator methods like >.
The plain . still raises
Shows plain . raising NoMethodError on nil and explains &. as a single nil check before the call.
Combining &. with || for defaults
Combines &. with || to supply default values, and explains why || also replaces a legitimate false answer.
When &. is the wrong tool
Separates legitimately optional values from values that should never be nil, and shows when &. hides a bug.
Safe navigation in this app's code
Reviews real uses of &. in the app's code, including a call where .presence already handles nil safely.
Putting safe navigation together
Summarizes the course in one table covering chains, arguments, plain dot, defaults, hidden bugs and real examples.