Ruby - Blocks and Block Parameters

Introduction

Ruby body of an iterator is called a block.

Any variables declared between upright bars at the top of a block are called block parameters.

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.

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

Demo

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

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

Result

Related Topic