Exploring Enumerable#map
Map is a method of the enumerable class. It is considered one of the most important functional methods in Ruby. It works by iterating over the elements of an array, returning an array which is composed of the results of the block that is executed on each element. If no block is provided an enumerator is returned for each element of the array. From Ruby Docs we see the following code example.
map { |obj| block } → array
map → an_enumerator
This will translate to these examples.
arr = [1,2,3,4]
arr.map { |num| num + 2 } #=> [3, 4, 5, 6]
arr.map { "horse" } #=> ["horse", "horse", "horse", "horse"]
When might you want to use this method. Well if you want to appy a block of code to each element, and return a new array that would then be used elsewhere, that would be a good use. Or you could use the map! method to alter the original array. The code below shows that you could use the map! to capitalize names in an array.
arr2 = ["john", "mary", "anne"]
arr2.map! { |name| name.capitalize } #=> ["John", "Mary", "Anne"]