How Does Array#map Work in Ruby?

Array#map explained

In Ruby, you can use two variants of map on an Array:

  • mapdoes not mutate the original array;
  • map! — mutates the original array.

You can call either one with a block (i.e. code within {...}). It has the following syntax:

array.map { |item| ... }

This would run the specified block for each element of the array.

Consider, for example, the following where map returns a new array of numbers with 1 added to each number from the original array:

nums = [1, 2, 3]
new_nums = nums.map { |num| num + 1 }

print nums #=> [1, 2, 3]
print new_nums #=> [2, 3, 4]

Similarly, the following example uses map!, which does the same thing, but it mutates (or modifies) the original array:

nums = [1, 2, 3]
new_nums = nums.map! { |num| num + 1 }

print nums #=> [2, 3, 4]
print new_nums #=> [2, 3, 4]

If you need to access the index while using Array#map (or Array#map!), then you can do so with the with_index method.

Array#map (or Array#map!) can also be used in a shorter syntax.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.