O'Reilly logo

Mastering Ruby Closures by Benjamin Tan Wei Hao

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required