Let's look the map
and collect
methods to gain a better understanding of each of them before integrating them together.
map
methodBoth map
and collect
are looping methods that can be used interchangeably in Ruby.
The map
method features enumerable objects like arrays, hashes, and ranges. It loops through each element of the enumerator object while applying a block of code and returns a new array with those results. This method is mainly used for data transformation.
The syntax of the map
method is as follows:
array.map { |element| block_of_code }
To better grasp the map
method, let's look into the following example:
input_array = ['x','y','z']output_array = input_array.map{ |elm| elm.upcase }print output_array
Let's explain the above code snippet:
Line 1: We define an array of strings. An Array is construed as an ordered, integer-indexed collection of objects, called elements.
Line 2: We call the map
method with the related block of code defined between brackets. Here, we are converting each element characters to uppercase.
Line 3: We display the resulting array.
with_index
methodThe with_index
method iterates over the elements of an enumerator object with an index and passes two parameters to the block of code. The first is the element value and the second is the index. It accepts an optional argument start index
, which specifies the index starting value.
The syntax of this method:
array.with_index(start index){ |elm,index| block_of_code }
This method does not collect the results. On the other hand, the map
generates and stores the resulting array.
input_array = ['x','y','z'].to_enuminput_array.with_index(1) { |elm,index| puts "index: #{index} for #{elm}" }
Let's break down the above code snippet:
Line 1: We create an enumerator object based on an array of strings.
Line 2: We apply the with_index
method while specifying 1
as a value for the starting index to iterate over the elements of our array and print out the index and the value for each element.
Suppose you are using the map
method and need the index of the element that you are iterating over to chain both methods together as follows:
array.map.with_index(start index) { |element , index| block_of_code }
input_array = ['x','y','z']output_array = input_array.map.with_index(1) { |elm, index| [index , elm.upcase] }print output_array
Let's go over the above code snippet to see how combining both methods together generated an array featuring indexes:
Line 1: We define an array of strings.
Line 2: We apply both methods map and with_index
together while specifying 1
as a starting index for the with_index
method. Such a combination will allow us to manipulate the element value and the index within the block of code. As you see, we are just converting the element characters to uppercase in the code block.
Line 3: We display the resultant array.
Free Resources