Map, the Number One Enumerable Method

~ Written as part of my coursework at Dev Bootcamp ~

December 11, 2015

The Enumerable module brings many useful methods to Ruby. One of the most widely used is map.

The map function has a twin named collect which performs the same function. However, the keyword map is conventionally used most often so that's the one that I'll focus on.

When map is run on a hash or array, it will run a block of code on every element and automagically insert the results of running that code into an array. If you add the 'bang' (!) symbol at the end (so map becomes map!), it even transforms the original array or hash.

One could actually acheive a similar feet with the simpler method of each, but it's more work and less elegant. For example, if running each to turn an array of integers into strings, one must first create a new or temporary array, run the to_s method on each element to convert it, then insert that converted element into the temporary array, and finally return the temporary array. It would probably look something like this:

        
          num = [1, 2, '3', 4, '5', '6']
          puts "Before method is run: " + num.inspect
          temp_array = []
          num.each {|number|
                int = number.to_i
                temp_array << int
          }
          puts "After method is run: " +  temp_array.inspect
        
      

Result:

        
          Before method is run: [1, 2, '3', 4, '5', '6']
          After method is run: [1, 2, 3, 4, 5, 6]
        
      

We can use map to accomplish the same feet, with the exact same output, and cut out a few lines of code along the way:

        
          num = [1, 2, '3', 4, '5', '6']
          puts "Before method is run: " + num.inspect
          array = num.map {|number| number.to_i}
          puts "Before method is run: " + array.inspect
        
      

Cutting out a few lines of code is always a nice way to end a blog post.