6 Control-flow techniques
This chapter covers
- Conditional execution
- Loops and looping techniques
- Iterators
- Exceptions and error handling
As you’ve already seen in the case of method calls—where control of the program jumps from the spot where the call is made to the body of the method definition—programs don’t run in a straight line. Instead, execution order is determined by a variety of rules and programming constructs collectively referred to as control-flow techniques.
Ruby’s control-flow techniques include the following:
- Conditional execution—Execution depends on the truth of an expression.
- Looping—A single segment of code is executed repeatedly.
- Iteration—A call to a method is supplemented with a segment of code that the method can call one or more times during its own execution.
- Exceptions—Error conditions are handled by special control-flow rules.
6.1 Conditional code execution
6.1.1 The if keyword and its variants
6.1.2 Assignment syntax in condition bodies and tests
6.1.3 case statements
6.2 Repeating actions with loops
6.2.1 Unconditional looping with the loop method
6.2.2 Conditional looping with the while and until keywords
6.2.3 Looping through an array of values with for
6.3 Iterators and code blocks
6.3.1 The ingredients of iteration
6.3.2 Iteration, home-style
6.3.3 The anatomy of a method call
6.3.4 Curly braces vs. do/end in code block syntax
6.3.5 Implementing times
6.3.6 The importance of being each
6.3.7 From each to map
6.3.8 Block parameters and variable scope
6.4 Error handling and exceptions
6.4.1 Raising and rescuing exceptions
6.4.2 The rescue keyword to the rescue!
6.4.3 Debugging with binding.irb
6.4.4 Avoiding NoMethodError with the safe navigation operator
6.4.5 Raising exceptions explicitly
6.4.6 Capturing an exception in a rescue clause
6.4.7 The ensure clause
6.4.8 Creating your own exception classes
6.5 Summary