The Map method

May 3, 2015

The Enumerable module in Ruby is probably the reason a lot of Ruby developers don't rely on conventional for loops much. They provide really convenient ways to traverse, search, sort, and manipulate collections. Here, I'm going to look at the map method. The map method executes a given block for each element of an array or hash, and will actually return a new array. It will not, however, manipulate the original array unless you use map!, which indicates it's destructible (we won't get into that for now). I'll demonstrate two use examples.

Example 1: Let's say we have a hash called artists and we wanted to print out all the artists whose genre is "hip hop." You would use the following block to iterate through your hash with the desired results:

Not only will our map example here print the artists who correspond to hip hop, but it will also return a new array of what was executed from the block, hence the returned array of: # => [nil, nil, "Gangstarr", nil, nil, "Quasimoto", nil]. Pretty cool, huh? The each method will do the same thing, but it will return the original array (or hash).

Example 2: Another use of map involves simple operations. I was inspired by a fun example using food and calories. I modified mine for desserts and grams of sugar. We can use map to divide each value in half, where the key is the dessert, and the value is the amount of sugar in grams. Check it out:

This example returned an array containing a set of two-item arrays, each of which corresponded to the key/value pair in our grams_sugar hash.

That's all for now. Hope you learned something! :-)