6 Control-flow techniques
Ruby control flow is built around the idea that programs do not simply execute in a straight line; instead, execution can branch, repeat, hand off control to blocks, or jump into error-handling paths. The chapter introduces the major categories of flow control—conditional execution, looping, iteration, and exceptions—and emphasizes that each is essential to writing idiomatic Ruby. It also highlights Ruby’s flexible syntax, where many constructs can be written in multiline, single-line, or modifier form depending on what reads best.
Conditional logic is explored first through if, else, elsif, unless, and case. The discussion shows how Ruby evaluates conditions, how negation works, why parentheses often improve clarity, and how modifier forms can make simple tests concise. It also explains subtle parsing behavior, such as assignments inside conditions and how Ruby warns about likely mistakes. For case, the key insight is that matching is driven by ===, which means classes and objects can define their own matching behavior and thereby customize how they participate in branching logic.
The latter part of the chapter moves from repetition to iteration and then to exception handling. Ruby’s looping tools include unconditional loops, condition-controlled loops with while and until, and collection traversal with for, but the deeper Ruby hallmark is the iterator/block pattern: methods like each, times, and map yield control to caller-supplied code and can be reimplemented in terms of one another. The chapter then closes with exceptions, showing how Ruby raises runtime errors, how rescue intercepts them, how ensure guarantees cleanup, how to inspect exception objects, and how to define custom exception classes for clearer, more precise error handling.
Summary
- “Control flow” refers to the order in which code statements get executed, and the dynamics that determine that order at runtime.
- Conditionals move control around based on the Boolean value (truth or falsehood) of expressions.
- Loops repeat a segment of code unconditionally, conditionally, or once for each item in a list.
- Iterators are methods that yield to a code block you provide alongside the call to the method.
- Exceptions are Ruby’s mechanism for interrupting program flow under error conditions.
- The rescue keyword grabs control when exceptions are raised and allows graceful recovery.
- You can create your own exception classes, by inheriting from Ruby’s exception classes.
FAQ
What are the main control-flow techniques covered in Chapter 6?
Ruby’s main control-flow techniques in this chapter are conditional execution, looping, iteration with code blocks, and exception handling. These let a program choose between paths, repeat code, yield control to blocks, and handle errors gracefully.How does if work in Ruby?
if executes its body only when its condition is true. Ruby also supports else for the false case and elsif for additional branches. If no branch matches and there is no else, the statement evaluates to nil.What is the difference between if, unless, and conditional modifiers?
unless is the negative form of if; it runs when the condition is false. Conditional modifiers place if or unless after a statement, making simple one-line conditions more concise. They are best for short, readable statements without branching.How does Ruby handle operator precedence with ! in conditions?
The ! operator has higher precedence than comparison operators like ==. That means !x == 1 is parsed differently than you might expect. Using parentheses, such as !(x == 1), is the safer and clearer style.How does a case statement decide which when clause matches?
A case statement compares its target expression against each when clause using the === method, also called threequal. The first matching when wins, and only that branch runs.Can Ruby objects customize how they behave in case statements?
Yes. Since case/when relies on ===, a class can define its own === method to control matching behavior. This lets your objects participate in case logic in a custom way.What is the difference between loop, while, and until?
loop runs indefinitely until you stop it with something like break. while repeats as long as a condition is true. until repeats until a condition becomes true, which is the reverse of while.What is the role of blocks and yield in iteration?
A block is code supplied with a method call, and yield lets the method execute that block. This is the core of Ruby iteration: the method controls when the block runs, and the block can receive values from the method.How do each and map differ?
each yields each item in a collection and returns the original collection. map also yields each item, but it collects the block’s return values into a new array and returns that array.How do exceptions and rescue work in Ruby?
When Ruby encounters a runtime problem, it raises an exception. A rescue clause can catch that exception and allow the program to continue or handle the error. You can also use ensure for cleanup, create custom exception classes, and use the safe navigation operator &. to avoid NoMethodError on nil.
The Well-Grounded Rubyist, Fourth Edition ebook for free