Block Pattern #1: Enumeration
You may have fallen in love with Ruby because of the way it does enumeration:
| >> %w(look ma no for loops).each do |x| |
| >> puts x |
| >> end |
| look |
| ma |
| no |
| for |
| loops |
| => ["look", "ma", "no", "for", "loops"] |
Besides being very expressive, enumeration using blocks is more concise and less error-prone. It is concise because the block captures exactly what we want to do with each element (printing it out to the console). It is less error-prone compared to traditional for loops because it does away with indices that are prone to the infamous off-by-one error.
You should be familiar with this way of iterating over a collection, such as an Array. What is interesting is how these methods are
Get Mastering Ruby Closures now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.