Enumerables is a Ruby Module that contains a collection of abilities to do search and sort on a block or array. You can do things like group by, find, reject and sort among other things. Today we’re going to take a look at Enumerable#map

Buttons

The map method takes an enumerable object and a block, and runs the block for each element, outputting each returned value from the block.

[1,2,3,4].map {|n| n*2}
# => [2,4,6,8]

You can also do a map! (with the exclamation mark) and it will become destructive, replacing the array that was used with the map! function.

When am I ever going to need to use map? Say you want to convert an array of number grades into an array of letter grades. We can use map to do that.

def letter_grade(number)
  case number
  when 90..100
    return "A"
  when 80..89
    return "B"
  when 70..79
    return "C"
  when 60..69
    return "D"
  else
    return "F"
  end
end
 
number_grades = [87, 81, 93, 79, 67, 41, 95, 77, 73, 100]
letter_grades = number_grades.map {|n| letter_grade(n)}
 
print letter_grades
# => ["B", "B", "A", "C", "D", "F", "A", "C", "C", "A"]

You might think, why use map instead of each? Well each is also part of enumerables, but it wont return an array with your results

[1,2,3,4].each {|n| puts n*2}
# Outputs:
# 2
# 4
# 6
# 8