1 March 2015


Enumerable Methods: Map


Hello all! Hope your weekends were great! Today I'd like to teach you about an important enumerable method known as the "map" method.

We've already learned that ruby uses arrays and hashes to store large collections of data. While that's great, there must me more we can do with arrays and hashes than just use them to store data. What if we wanted to take all of that data and transform every single element in a collection into something completely new with a single line of code? Is that even possible? The answer is unsurprisingly a resounding YES!

Through the used of enumerable methods we are able to iterate through every piece of data in an array or hash and transform it into something completely new. The word "iterate" is often used in coding and pretty much just means to create a new version of something. So when we iterate through an array using an enumerable method, we are creating a new version of that array.

The map method, more specifically, allows us to take an array/hash and run a block of code on each and every element, thus creating a new collection of data.

Here's how it works.

We start with an array:

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

We decide we want to do something to that array, for instance multiply every number by 100, so we call upon the map method.

new_array = array.map {|i| i * 100}

The bit in the curly braces {} is our code block and it can be anything we want it to be depending on how we want to transform our array. That | i | is a variable we use to represent each element in the array. And i * 100 is telling ruby to iterate through the array and multiply each element in the array by 100.

The result we get is a completely new and separate array that looks like this:

new_array = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]

And if we still want our old original array, we can still access that too, because the map method is a non-destructive method, meaning it doesn't destroy our original.

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

And that's the map method!

- S.G.

Prev Next