Each, Map, Select, Collect and other Enumerable methods

Each & Map

Enumerable#each executes the given block for each element of the array, then returns the array itself.

Enumerable#map also executes the given block for each element of the array, but returns a new array whose values are the return values of each iteration of the block.

Example: assume you have an array defined thusly:

arr = ["tokyo", "london", "rio"]

Then try executing each:

arr.each { |element| element.capitalize }
# => ["tokyo", "london", "rio"]

Note the return value is simply the same array. The code inside the each block gets executed, but the calculated values are not returned; and as the code has no side effects, this example performs no useful work.

In contrast, calling the array’s map method returns a new array whose elements are the return values of each round of executing the map block:

arr.map { |element| element.capitalize }
# => ["Tokyo", "London", "Rio"]
the above lines can also be written as
arr.map(&:capitalize)

Each_with_index

Sometimes you also want to know what position in the array you are… so that sounds like a good chance to use Enumerable’s#each_with_index, which will pass that position into the block as well.

Select

Enumerable’s #select: It will run the block on every item of your object (whether array or hash or whatever) and return a new object that contains only those items for which the original block returned true:

> my_array = [1,2,3,4,5,6,7,8,100]
> my_array.select{|item| item%2==0 }
=> [2,4,6,8,100]

Collect

Enumerable #collect is the same thing as #map.

Enumerable Iterators Cheat Sheet

  • #each returns the original object it was called on because it’s really used for its side effects and not what it returns
  • #each_with_index passes not just the current item but whatever position in the array it was located in.
  • #select returns a new object (e.g. array) filled with only those original items where the block you gave it returned true
  • #collect is the same as #map.
  • #map returns a new array filled with whatever gets returned by the block each time it runs.
Like what you read? Give Shadeslayer a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.