Enumerable Methods/ #map
January 31, 2016
Alyssa Page
A module in Ruby is a bunch of methods that have been packaged together. The Enumerable module is one that is accessible as long as the class that wants to include it has its own #each method. This is because all enumerable methods are based off of #each and are used to traverse, search, sort and manipulate collections.
One of the many available methods in enumerable is #map (or collect). Map allows you to transform a copy of an object without altering the original.
Say we have the array
user_names = ["Harry", "Ron", "Ginny", "Hermione"]
and we want to have a copy of this array with all the elements in uppercase. Using #map will allow you to transform a copy and still have the original copy unaltered for later use. Since the array class has it's own each method the enumerable methods are accesible.
caps_names = user_names.map { |item| item.upcase }
puts user_names --> Harry Ron Ginny Hermione
puts caps_names --> HARRY RON GINNY HERMIONE
So you can see that in this case map has returned a new array filled with what the code block returns each time it runs.