Comparing Iterations..What is the Difference of Each Outcome!

Do you know when to use Rubys Map, Each, or Select Method?

When I first started out, I had not one clue about coding and software engineering at all… I just knew that this is the future, and you either evolve with the times or become extinct just like the dinosaurs did. So I made the move, and here I am!

I have been fortunate to work with a great team, and most importantly a wizard of a senior cohort leader who is a wizard when it comes to working with arrays amongst a s*** load of other things in this digital arena of software engineering. He taught me all the best practices to sufficient, clean, dry code especially when it came to arrays. Here are the methods that I find the most useful and I think are good to have in your Ruby toolbox right from the start to name a few…

each

Before we dive into some of the fancier methods above, we first need to start with the most basic, each. each will call a block once for every given element in an array. When it is done, it will return the original array. That last part is key and is easy to forget. Even those of us who have been working with Ruby for a while sometimes forget it. Here is an example..

each method

map

I learned there was a better way, and that is by using map. map returns a new array with the results of executing the block once for every element in your original array. Here is an example:

map method

We add 2 to every number in our original array and then group those results up into a new array, which is returned.

select

select returns an array containing all elements for which the given block returns a true value.

select method

1:

each will call a block once for every given element in an array. When it is done, it will return the original array. .

2:

map is going to add 2 to each of our array elements and return [3, 4, 5, 6].mapwill also prepend "hi" to that 4 and return ["hi 4"]

3:

select will select only the even numbers from that array and return [4, 6].