Eunice Choi
Web Development Student | Dev BootCamp SF

Enumerable #map


September 20, 2015

If you look up the definition of enumerate on Google, you will see that one of the definitions is: "to mention (a number of things) one by one". In Ruby, an enumerator is a tool that is used to access each item, or element, in a collection, such as an array or hash.Enumerable is a Ruby module, which exists in the Array class. You may have heard of the Enumerable module being a mixin. This simply means that it is "mixed in" or included in the Array class, allowing its instance variables to be used as available methods in the class.


Enumerables provide a variety of enumerators methods, such as map, to help with iteration. For a class to use Enumerables, it must define an #each method. For example, the Array class, which uses Enumerables, defines the each method. This allows you to perform enumerators as you sort through each element in an array.


Enumerable#map


.map is an Enumerable method that allows you to return a new array with the results from iterating through a list or some sort. Let's say that you want to sort through the given range of a number and multiply each integer in the range by 2. For instance, you have a given range 1..3, which includes the integers: 1, 2, and 3. Multiplying each integer by 2 would return: 2, 4, and 6.


We can't use .each to iterate through the range since the integers within the range is not in an array. What you CAN use is .map:

(1..3).map { |i| i*2 }      #=> [2, 4, 6]

Writing .map is similar to writing the .each method. You add .map next to the list you want to sort through and then write what actions you want to perform to each element in curly braces. The results are then inserted into a new array!


Enumerable#map is also used to sort through arrays themselves. This is useful when you want to create a new array with the results from iteration. You might wonder why we just can't use.each? This is because .each can run through an array and pass in each element as an argument, but it does not save the results into a new array.

[1, 2,3].map { |i| i*2 }    #=> [2, 4, 6]