Ruby - Blocks and Array Collect method

Introduction

Blocks are commonly used to iterate over arrays.

The Array class provides a number of methods to which blocks are passed.

collect method 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:

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 letter is capitalized:

b4 = ["hello","good day","how do you do"].collect{|x| x.capitalize }

So, b4 is now as follows:

["Hello", "Good day", "How do you do"]

Related Topic