For each, Map, Collect, Select,Find_all, Find, Reduce in Ruby

Sekou Dosso
4 min readOct 26, 2020

FOR EACH

The each iterator returns all the elements of an array or a hash.Executes code for each element in collection. Here, collection could be an array or a ruby hash.

It’s does not alter the original argument

Syntax

MAP

Map is a Ruby method that you can use with Arrays, Hashes & Ranges.The main use for map is to TRANSFORM data.

Ruby Map vs Each

What is the difference between map & each?

Each is like a more primitive version of map…

It gives you every element so you can work with it, but it doesn’t collect the results. Each always returns the original, unchanged object.

While map does the same thing, but… It returns a new array with the transformed elements.

Ruby Map vs Collect

Map and Collect are exactly the same method.

They are different names for the same thing!

COLLECT

Array#collect() : collect() is an Array class method which invokes the argument block once for each element of the array. A new array is returned which has the value returned by the block.

Syntax:

Array.collect()

Parameter: Arrays in which we want elements to be invoked

Return: array with all the invoked elements

Select / FIND_ALL

SELECT or FIND_ALL is best used when you need to iterate over an array or hash but only need the elements that return true when tested.

SELECT and FIND_ALL are basically identical when it comes to working with arrays.

Important

When it comes to iterating over hashes, this is when we see the difference between .select and .find_all.

Notice how in the above example how both the .

select and .find_all return the same key:value pairings but

.select returns the value in the form of the original input which in this case is a hash. But we can see that .

.find_all return the key:value pairing in an array.

FIND

find(p1 = v1) public

Passes each entry in enum to block.

RETURNS THE FIRST FOR WHICH BLOCK IS NOT FALSE

If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise.

If no block is given, an enumerator is returned instead.

SELECT vs FIND

The .find method

This Ruby method iterates through an array and gives you the first match for which the expression within a block returns true.

The .select method

The .select method iterates on an array or hash and returns an array or hash (depending on the datatype) of all values that evaluate as true given a block of code.

This method is great when you want to filter a list and only return values that match certain conditions.

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

REDUCE

The ‘reduce’ method can be used to take an array and reduce it to a single value.

--

--