Map method in Javascript and Ruby

Tags: javascript, ruby
Publish Date: 2014-11-06

The map method in Ruby (defined in the Enumerable module) is one of the most commonly used methods among Ruby developers. However, in the Javascript world, it only became cross-browser compatible since IE9.

In Ruby, #map allows you to run a block of code on every element in an "enumerable object" and returns the results in an Array.
By an "enumerable object", I mean Ruby classes that includes the Enumerable module, such as Array, Hash and Set.

In the following example, we have a 2-dimensional array, in which every sub-array contains the first name and last name as two separate array elements. By providing a block of code to the map method, we can return the full names as a string and store them in an array.

  split_names = [ ["Carmelo", "Anthony"], 
                  ["Rajon", "Rondo"], 
                  ["Tim", "Duncan"], 
                  ["Derrick", "Rose"] ]

  names = split_names.map{ |elem| "#{elem[0]} #{elem[1]}" }

  names #=> ["Carmelo Anthony", "Rajon Rondo", "Tim Duncan", "Derrick Rose"]

In Javascript, the same can be done with the map method, which takes an annonymous function:

  var split_names = [ ["Carmelo", "Anthony"], 
                      ["Rajon", "Rondo"], 
                      ["Tim", "Duncan"], 
                      ["Derrick", "Rose"] ]

  var names = split_names.map(function(elem){
    return elem[0] + " " + elem[1];
  });

  names #=> ["Carmelo Anthony", "Rajon Rondo", "Tim Duncan", "Derrick Rose"]

In Ruby, instead of providing a block to the map method, we can also use a "shortcut", IF the block of code we want to run is a method that every element can respond to.
Let's say from the previous 2-dimensional array, we only want the last names instead of the full names.
We can grab the last names by calling #pop on every element.

  split_names = [ ["Carmelo", "Anthony"], 
                  ["Rajon", "Rondo"], 
                  ["Tim", "Duncan"], 
                  ["Derrick", "Rose"] ]

  names = split_names.map(&:pop) # shortcut for map{ |elem| elem.pop }

  names #=> ["Anthony", "Rondo", "Duncan", "Rose"]