Each, Collect, Map, Select, Find, Find_all….Oh My!

As I dive deeper into Ruby, iterators are used more frequently to retrieve data stored in the arrays. Some data could be stored deep down in the ocean (nested data) which means I will have to iterate over the arrays few times to get the information I need.

So, the big question is, which iterator or iterators should I use?

The bigger and more important question is, will it return the value or just print them?

I also wondered if others are struggling as well. So, in attempt to help myself as well as others, I have decided to blog about it.

Ruby has many built-in methods, but here are few iterators that has been used frequently: each, collect, map, select, find, and find_all.

These built-in methods iterate through each element in a collection, and do some magic work and returns the transformed data for us to use. Well, some do and some do not.

.each:

It does not transform the original data. We can print the result after code execution is done, but #each always return the original data.

.collect and .map:

collect and map are the same. Unlike each, these two always return new transformed data. After iterating over each element in a collection, it will return the same number of elements as in the original collections.

.select:

select act as a filter machine. As code executes, it collects only the element that returns a true value. Then, it return new collection of elements.

.find:

find returns first element that is true. The first element that matches the executed code. If nothing meets the criteria, it will return nil.

.find_all:

find_all returns all element that is true after iterates over a collection. It does same thing as #select.