Enumerable Method - Map
Nichole Shelton
November 23, 2014
What's an Enumerable?
By definition an enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. In plain English an enumerable allows the programmer to perform various functions on each element in a hash or an array. Pretty nifty right?Each Method
So by now you're pretty familiar with the .each method right? The each method allows the programmer to iterate through an array or hash and perform said action to each element within the aray or hash. Enough talk, let's look at some code.
thanksgiving_dinner = ["Turkey", "Stuffing", "Mac n Cheese", "Cranberry Sauce"]
thanksgiving_dinner.each {|food| food + "makes me think of Thanksgiving."}
=> ["Turkey", "Stuffing", "Mac n Cheese", "Cranberry Sauce"]
As you can see from the output, the each method simply returns the original array. Each will not modify your array. That is why we have the map method.
Map Method
The map method is awesome. Oh how I wish i knew about it earlier this week. Ce la vie. The map method iterates through the array AND it returns a modified copy of the result of the block AND it doesn't make changes to the original array. Can you say amazeballs? Let's check out the code.
thanksgiving_dinner.map {|food| food + " makes me think of Thanksgiving."}
=> ["Turkey makes me think of Thanksgiving.", "Stuffing makes me think of Thanksgiving.", "Mac n Cheese makes me think of Thanksgiving.", "Cranberry Sauce makes me think of Thanksgiving."]
And you can see when I call the array it is unchanged.
thanksgiving_dinner
=> ["Turkey", "Stuffing", "Mac n Cheese", "Cranberry Sauce"]
Hope you find this useful!

