a collection of my projects and thoughts as I wade through #devbootcamp

Enumerable#Map

Ruby's way of changing collections

14.12.2014

First off, Enumerable is module in Ruby that works for collections of things. That mean you cannot apply any of its methods to single things, (like a string, or a number). You use enumerable methods to collections of data, like hashes or arrays.

There is a long list of Enumerable methods, such as: each, drop, find, grep, and reject. Today, however, I want to focus on map, as I conside it to be one of the most important and basic enumerable methods.

Map Basics

  1. Map loops through an objects elements and applies a change, specified by a block of code.
  2. Map will always return an array.
  3. Map will return in the original length.

For example, let us pretend you are sending out a bunch of emails to the parents of your failing students to warn them that their children are not doing well. You have a list, (in an array of course, of all the students last names.

>> failing_names = ["johnson", "SMITH", "Rodriguez", "LEE", "Bell", "lopez", "kim"]

If you are auto inserting their last names into an email, you'll be looking unprofessional if you insert the names as they are: some in all caps or all lowercase. For this, you can use the enumerable method map to loop thorugh them and make them all one format. Simple use the capitalize method on each name.

>> failing_names.map {|last_name| last_name.capitalize}
=> ["Johnson", "Smith", "Rodriguez", "Lee", "Bell", "Lopez", "Kim"]


Ta-da! Your names are all in proper format. So what did you do? You called map on the array (failing_names.map). In the block following, (everything inside the {}), you asked the code to takee each item in the array, (last_name), and capitalize it. Since map always returns an array, you now have a new array with each last name capilatized!

NOTE: In order to permanently save these changes you must use the desturctive map! method or push the results into a new array. Otherwise, next time you call the array, it will go back to the original, unformatted version.


Return to list of blog posts.