Cover by Michael Fitzgerald

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

O'Reilly logo

Blocks

A block in Ruby is more than just a code block or group of statements. In a certain context, a block has a special meaning. This kind of block is always invoked in conjunction with a method, as you will see. In fact, it is referred to as a nameless function.

A block in Ruby is often (but not always) an idiom for getting all the values out of a data structure by iterating over the structure. It sort of means, "give me everything you've got in there, one at a time." I'll show you a common use of the block.

Remember the array pacific? Here it is again:

pacific = [ "Washington", "Oregon", "California" ]

You can call a block on pacific to retrieve all of its elements, one at a time, with the each method. Here is one way to do it:

pacific.each do |element|
 puts element
end

The name between the pipe characters (|element|) can be any name you want. The block uses it as a local variable to keep track of every element in the array, and later uses it to do something with the element. This block uses puts to print each element in the array:

Washington
Oregon
California

You can replace do/end with a pair of braces, as is commonly done, to make things a bit tighter (by the way, braces actually have a higher precedence than do/end):

pacific.each { |e| puts e }

Many dozens of classes have each methods in them, such as Array, Hash, and String. But don't get the wrong idea. Iterating over data structures isn't the only way to use blocks. Let me give you a simple example using yield, a Ruby keyword. ...

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