The map Method in Ruby

Nurudeen Ibrahim Apr 18, 2022
The map Method in Ruby

The map method is one of Ruby’s most popular enumerable methods. It’s used to transform an array into another one.

Example Codes:

numbers = [2, 4, 6]

doubles = numbers.map do |n|
  n * 2
end

puts doubles

Output:

[4, 8, 12]

The above code maps through the numbers array, multiply each element by two, and produce a new doubles array. This is how the map method works.

Note that there is also a collect method, an alias to map, and both work similarly. We can show that by rewriting the above code using the collect method.

Example Codes:

numbers = [2, 4, 6]

doubles = numbers.collect do |n|
  n * 2
end

puts doubles

Output:

[4, 8, 12]

Although the map method produces a new array, there’s also a map! which works the same way as map but also mutates the original array.

Example Codes:

numbers = [2, 4, 6]

doubles = numbers.map! do |n|
  n * 2
end

puts doubles
puts numbers

Output:

[4, 8, 12]
[4, 8, 12]

Looking at the output above, you would notice that the original numbers array has been mutated and now has the same value as doubles.

Related Article - Ruby Map