Chapter 2Beautiful Blocks

Blocks are effectively a type of closure. Blocks capture pieces of code that can be passed into methods to be executed later. In a sense, they act like anonymous functions.

Blocks are ubiquitous in Ruby and are one of the defining characteristics of Ruby—you can immediately tell that it’s Ruby code once you see the familiar do ... end or curly braces. It’s virtually impossible to write any meaningful Ruby program without using blocks. In order to understand and appreciate real-world Ruby code, it’s imperative that you understand how blocks work and how to use them.

Rubyists often wax lyrical about blocks—and for good reason. They are a powerful language construct that leads to beautiful and succinct code. They ...

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.