Blocks and Block Parameters

In Ruby, the body of an iterator is called a block, and any variables declared between upright bars at the top of a block are called block parameters. In a way, a block works like a function, and the block parameters work like a function’s argument list. The each method runs the code inside the block and passes to it the arguments supplied by a collection (such as the array, multiarr). In the example from the previous section, the each method repeatedly passes an array of four elements to the block, and those elements initialize the four block parameters, a, b, c, d. Blocks can be used for other things, in addition to iterating over collections.

Ruby also has an alternative syntax for delimiting blocks. Instead of using do..end, you can use curly brackets {..} like this:

block_syntax.rb

# do..end
[[1,2,3],[3,4,5],[6,7,8]].each do
   |a,b,c|
     puts( "#{a}, #{b}, #{c}" )
end

# curly brackets {..}
[[1,2,3],[3,4,5],[6,7,8]].each{
   |a,b,c|
     puts( "#{a}, #{b}, #{c}" )
}

No matter which block delimiters you use, you must ensure that the opening delimiter, { or do, is placed on the same line as the each method. Inserting a line break between each and the opening block delimiter is a syntax error. I’ll have more to say on blocks in Chapter 10.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.254.61