Michael Fitzgerald

Michael Fitzgerald is Principal at Overdue Books LLC, a publishing and writing firm. He is the author of Learning Ruby, Ruby Pocket Reference, XML Pocket Reference, Third Edition with Simon St. Laurent, XML Hacks, and Learning XSLT, all published by O'Reilly. He is also the author of Building B2B Applications with XML: A Resource Guide and XSL Essentials (both by John Wiley & Sons). His books have been translated into Spanish, Portuguese, French, German, Polish, Korean, Japanese, and Chinese. He was a regular contributor to XML.com. He blogs at www.michaeljamesfitzgerald.com. Michael likes to ski (downhill and cross country), ride and train horses, run, and spend time with his family.

Blocks in Ruby

A fundamental Ruby idiom explained.

When we talk about blocks in Ruby, we’re not usually talking about code blocks — or blocks of statements — as we might with other languages. We’re talking about a special syntax in Ruby, and one of its idioms. I’ll be discussing blocks in this article, plus a little about procs and lambdas.

Ruby’s blocks are always associated with methods, which are sets of recallable procedures. Blocks can’t get along very well by themselves. They are dependent on methods, which normally feed data to them. Without that data, a block can’t do anything useful. It needs a parent to look after it.

Blocks are anonymous and are sometimes referred to as nameless functions. Blocks are like methods within another method that grab data from an enclosing method. If all this is unfamiliar to you, it may not make sense. Keep reading and I’ll do my best to clear things up for you.

Read more…