Blog

Array cartography


Week 4


Ruby's "map" method


October 10, 2014


Ruby’s Enumerable#map method is a powerful tool that you can apply to an enumerable, for example an array, that creates a new array with certain conditions for each element. It a very often-used method, and its flexibility makes it one of the best methods for modifying arrays.

Take the following example, for instance:


def map(array)

array.map{|num| puts num*2}

end


map([1,2,3,4,5])


Which would return this array:


[2,4,6,8,10]


As you can see, the “.map” method is applied to the original array [1,2,3,4,5]. The block that follows, within “{ }” is the part that actually modifies the array. Notably, map returns an entirely new array, [2,4,6,8,10], rather than modifying the original array. You could still access the original array just by typing “return array.”

To modify the original array, you would use “.map!” (with exclamation point) which is a destructive method that overwrites the original array with the resulting new array. For example, if you called “map!” on the above array, you would still get [2,4,6,8,10]. But if you called “return array” any time after calling “map!” you would get a padded array with “nil” as all the values. The original array doesn’t exist anymore because the modified array has taken its place.

Map is very helpful becasue you don’t have to define and specify a new array to put your modifications in. For example, if you were using the “.each” method, you would have to define a new array and append each element into the array, like so:


array = [1,2,3,4,5]

new_array = []

array.each{|num| new_array << num*2}


Of course, map can be used on any type of array, from strings to integers to combinations of both. Interestingly, the block of code doesn’t need to modify the elements, but can replace them entirely. For example:


[1,2,3].map[“number replaced!]


would return:


[“number replaced!”, “number replaced!”, “number replaced!”]

Map is also sometimes called “collect” and calling the “collect” method on an object does the same thing as map.

To use a more complicated example of “map,” can you guess what the following would return?


def map

array = %w[I am an angry array]

array.map!{|string| (string === "angry") ? "ANGRY" : string}.join(" ")

end


map


If you guessed “I am an ANGRY array,” you’re right!