Blocks

The use of blocks is fundamental to the use of iterators. In the previous section, we focused on iterators as a kind of looping construct. Blocks were implicit to our discussion but were not the subject of it. Now we turn our attention to the block themselves. The subsections that follow explain:

  • The syntax for associating a block with a method invocation

  • The “return value” of a block

  • The scope of variables in blocks

  • The difference between block parameters and method parameters

Block Syntax

Blocks may not stand alone; they are only legal following a method invocation. You can, however, place a block after any method invocation; if the method is not an iterator and never invokes the block with yield, the block will be silently ignored. Blocks are delimited with curly braces or with do and end keywords. The opening curly brace or the do keyword must be on the same line as the method invocation, or else Ruby interprets the line terminator as a statement terminator and invokes the method without the block:

# Print the numbers 1 to 10
1.upto(10) {|x| puts x }   # Invocation and block on one line with braces
1.upto(10) do |x|          # Block delimited with do/end
  puts x
end
1.upto(10)                 # No block specified
 {|x| puts x }             # Syntax error: block not after an invocation

One common convention is to use curly braces when a block fits on a single line, and to use do and end when the block extends over multiple lines.This is not completely a matter of convention, however; the Ruby parser binds { tightly ...

Get The Ruby Programming Language 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.