July 2011
Intermediate to advanced
400 pages
8h 46m
English
Blocks are commonly used to iterate over arrays. The Array class, consequently, provides a number of methods to which blocks are passed.
One useful method is called collect; this passes each element of the array to a block and creates a new array to contain each of the values returned by the block. Here, for example, a block is passed to each of the integers in an array (each integer is assigned to the variable x); the block doubles its value and returns it. The collect method creates a new array containing each of the returned integers in sequence:
2blocks.rb
b3 = [1,2,3].collect{|x| x*2}The previous example assigns this array to b3:
[2,4,6]
In the next example, the block returns a version of the original strings in which each initial ...
Read now
Unlock full access