In Ruby, you can use two variants of map
on an Array
:
map
— does 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.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.