The map method returns the result of evaluating the block for each element as a new array. The alias method is the collect method.
(Example) Code that creates a new array by trebling each element of the array
numbers = [1,2,3]
new_numbers = []
numbers.each { |n| new_numbers << n * 3 }
new_numbers #=> [3, 6, 9]
The map method creates a new array in which the return value of the block is an element of the array, so you can just put the return value of the map method into a new variable.
numbers = [1,2,3]
#The return value of the block becomes each element of the new array
new_numbers = numbers.map { |n| n * 3 }
new_numbers #=> [3, 6, 9]
In this way, you can use the map method to replace most of the work of preparing an empty array, looping through other arrays, and packing the results into an empty array.
Introduction to Ruby for those who want to become professionals
Recommended Posts