map
is another extremely useful Ruby iterator. It helps us map data from one form to another. It will return a new Array containing the result of running the specific block on each element in the collection. Let’s start with a simple example using an Array of numbers:
nums = [1,2,3,4,5]
If we wanted a new Array where every item is double the original item in nums
:
double_arr = nums.map {|num| num * 2}
map
will run num*2
on every item in the nums
Array, storing the result in a new Array. That new Array looks like this:
[2, 4, 6, 8, 10]