DEV Community

lycho33
lycho33

Posted on • Edited on

Cautionary Iterarty Tale

Alt Text
For Flatiron, I was in Phase 1 starting to go through labs and learn about Ruby. Of course loops and conditionals had their own challenges to adjust to, iterations seemed simple. You iterate through an array so that the block of code is executed for each array's element. But only after finalizing my CLI project do I now understand the importance of iterators.

Here is a list of iterators
1) .each
2) .map/.collect
3) .select
4) .detect
5) .delete_if
6) .find/.find_all

OUT of all of these arrays I had to learn which iterators would be most helpful for my code. And this is what I learned.

.each

This was deceivingly the most simple method. From numerous labs, I found that this method would be the most versatile to pass the labs. It allowed me to execute anything in the iteration bloc, while not easily breaking my program.

I already knew that the return for .each was the original array. But despite knowing this, I used this method in my class to extract my API methods and gather specific data. By doing so, I was not keeping my code DRY and putting in .each iterations that weren't doing anything for my program.

So the key lesson I needed to learn:

.each iterates over each array's element and executes the block's code BUT still returns the original array

   ##IF each was not going to do anything what should I use?
Enter fullscreen mode Exit fullscreen mode

.map/.collect

After calling my API and making it into a hash, my goal was to iterate to extract only a specific key and its associated values. So my next go-to would have been these methods. I was going to iterate to get the specific key-value pairs. And when I did... IT DIDN'T WORK!

What does it return?
.map/.collect returns a new array BUT + collect/map TRANSFORMS every array's element and doesn't extract the specific key-value pairs I needed.

   ##SO what did I need?
Enter fullscreen mode Exit fullscreen mode

.select

IT was this! Select returns a new array of elements that are true to the condition set in within the block. So if the key I needed matched the element, then it was TRUE and would be included in the new array.

  ##Question: Would .find_all had worked?
Enter fullscreen mode Exit fullscreen mode

.find_all

After investigating further, .find_all might not have worked because when iterating through a hash, find_all would return an array whereas select would return a hash still.

 ##What's the verdict of this challenge?
Enter fullscreen mode Exit fullscreen mode

Lesson: What return you want dictates what iterator you choose to use. It will be lesson not to forget. Though .each is versatile, it will not return a new array. So here is my cautionary tale that I hope others do not fall into. Heed my mistake and happy programming!

Top comments (0)