How to Use Ruby's Map Method

The map method is a non distructive enumerable method of Ruby's Array class or Enumerable#map in Rubyese. In a nutshell it will iterate over each element in an array and perform a function on each of these elements. It also has a corresponding destructive version Enumerable#map! if you need to change the original array and have it returned instead of returning a new one. It is a really handy method when you want to do 'something' to each element of an array. Take a look at the following examples to see what I mean.

numbers = [1, 2, 3] numbers.map { |num| num**2 } Output: [1, 4, 9]

Here the map method is used to square each number in the array.

names = ['liam', 'dustin', 'elisa'] names.map { |n| n.capitalize } Output: ['Liam', 'Dustin', 'Elisa']

Here the map method is used to capitalize each name in the array.

values = ['liam', 0.83, 'dustin', 31, 'elisa', 30] values.map { |v| v.to_s } Output: ['liam', '0.83', 'dustin', '31', 'elisa', '30']

Here the map method is used to convert each value in the array to a string.

That's it! A very simple yet powerful method to use anytime you need to do 'something' to each value within an array.