The Map Method: The Inside Scoop

11/23/2015

What is the Map Method, and why should I care?

The most common way you encounter iterating over collections is the use of the each method. While each is great there are other methods you can use depending on your desired result. One of those other methods is map. The map method allows you to iterate over a collection, execute the given code block, and return the result of that block. Where each and map differ is the return value. Each will execute the block, but the result of that execution is tossed out after the block has finished. The return value will be the orginal collection. If you want to use the results from the executed block, then you need to use map. One thing to note about map is that it always will return an array, even if the original object wasn't an array. The returned array will also be the same size as the original object.

Map vs Map!

Map is a non destructive method. Meaning that map does not destroy the original object. There is a destructive map method alternative though called map!. Map! is a method belonging to the array class, and not the enumerable module. This is because .map! does inplace mapping of the block results. This can only be done on an array. Since map can be used on other types of data structures you wouldn't be able to perform in place mapping. If you use .map! it's important to remember that the original data structure will be permanently replaced by the results of the code block.

Sooooo...what does the collect method do?

Collect is actually an alias of the map method. It also has a destructive method called collect!.