Control flow

A program decides and repeats, and this part is where it does both. Conditions and loops come first in their plain form, then the parts of Ruby that make them readable: case with its patterns, guard clauses and statement modifiers, the loop keywords break, next, redo and retry, and the boolean operators with safe navigation.

3.1 Conditions Branch code with if and else, flip checks with unless, chain elsif, and match values with case-when. Open 3.2 Loops Repeat work with while, until, for, each, and times in Ruby. Open 3.3 case and when in depth case compares with ===, so a when can hold a range, a class, a regex or a lambda; then and the missing else change nothing a reader expects. Open 3.4 Guard clauses and modifiers return unless and next if at the top of a method, one-line if and unless, and the point where a modifier makes code harder to read. Open 3.5 break, next, redo and retry loop do, break with a value, next, redo and retry: the four keywords that control a loop, and why each is preferred over for. Open 3.6 &&, ||, and, or and safe navigation Ruby has two sets of boolean operators with different precedence, an ||= that fills a default, and a &. that stops a nil from breaking a chain. Open

Lessons