Chapter 14Blocks and Procs

This is definitely one of the coolest features of Ruby. Some other languages have this feature, though they may call it something else (like closures), but most of the more popular ones don’t, and it’s a shame. And, in any case, Ruby makes it so pretty with its cute little syntax!

What is this cool new thing? It’s the ability to take a block of code (code in between do and end), wrap it up in an object (called a proc), store it in a variable or pass it to a method, and run the code in the block whenever you feel like it (more than once, if you want). So, it’s kind of like a method itself, except it isn’t bound to an object (it is an object), and you can store it or pass it around like you can with any object. I ...

Get Learn to Program, 2nd Edition 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.