Iterate with Each, Map & Select
What does the word Iterate mean?
-It means doing something multiple times.
Iteration in Ruby return all the elements of a collection one after another. Iterators are the methods which are supported by collections(Arrays, Hashes etc.). Collections are the objects which store a group of data members. As a software developer there will be times when you would want to repeat few functions over and over but it’s impossible to write them 100 or more times. That’s when the cool iteration tools will come and save you!
Differences between EACH, MAP & SELECT:
All of these three are part of ENUMERABLE methods. An ENUMERABLE basically gives you a way to repeatedly go through (iterate) an array or hash and do something to the elements contained within them.
Let’s take a closer look through each of them!
.each
.each method does whatever is specified to do for each element in an array and returns the same array. The block in method is what performs an operation on each element. The return value is the same thing that you called it on. To return a transformed array, you will gave to save the block into a variable and return it after the block.
In the example above on line no 1. I have an array of numbers. In line 3. It’s taking the each number from the array, multiplying it by 2 and outputting the result. But at the end it’s returning the same array!
.map aka .collect
.map returns an array of the same number of elements as the array on which you called it. It returns an array transformed elements in the original array. The block defines the transformation to be performed and specifies what is to be returned in the result.
In the example above, the . map method is going though each number, multiplying it by 2 and returning the result in a new array!
.select
.select is basically what it sounds like the word “select”. You can use this method when you need to iterate through and array but don’t want a whole array in return, instead you want a specific element or an array of elements which meets your conditions.
In the examples above, .select method is selected the elements from the arrays that matched the conditions and returned new arrays.
All of these methods can get a bit confusing at the beginning. It took me a pretty long time to get used to understanding which method to use when. So just keep on practicing and they will all make sense!
Thank you for reading this blog, and hope it can help you understand the methods better!
Also, here is a link which helped me a lot to understand these methods a lot!