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.
animals = ["owl", "dog", "bear", "rabbit"]def capitalize_names(animals) animals.each do |animal| puts animal.capitalize endend
.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.
def capitalize_names(animals) cap = animals.map do |animal| animal.capitalize end print cap return capend
.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.
def word_letters(animals) cap = animals.select do |animal| animal.length > 3 end print cap return capend
.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.
def word_letters(animals) cap = animals.find do |animal| animal.length > 3 end print cap return capend
.find_all:
find_all returns all element that is true after iterates over a collection. It does same thing as #select.
def word_letters(animals) cap = animals.find_all do |animal| animal.length > 3 end print cap return capend