Ruby Essentials .map : A Beginners Guide

Mo Zahid
3 min readJun 23, 2021

--

When starting on your journey as a Rubyist there are some fundamental methods that are absolutely essential to your development! The .map is definitely one of them.You will be using it a great deal and will learn a variation of it in other programming languages. It can take a little while to get used to but with repetition comes mastery! Buckle up, next stop is a tutorial on essential method .map within the world of Ruby!

.map

Whenever you need to transform an array or hash .map is the way to go. In this example we will be showing you how one can call .map on an array. Keep in mind that .map is non-destructive. It will always return a new array and does not change the original.

In the above example we have a simple array with a few integers called arr. Let’s say we want a new version of this array…a “transformed” version of this array. We simply write .map after the array we want to transform (line 3). The syntax after is curly braces with a pipe. What .map will do is go through this array one element at a time. That element is represented within the pipe as |num|. So for the first element in the array we have a 7. We are saying let’s take this 7 and add a 1 to it. Next .map does the same thing for the next element in the array (8) and so on. Once .map has reached the end of the array it will return a new array with the transformed numbers. We are assigning this new array to the variable arr2. When we run this code, we get the below:

ignore the bundle exec ruby main.rb

Awesome, looks like it worked! We now have a new array of transformed elements(8,9,19).

note: we are using curly braces in the example above because our code is fairly simple and it can all fit on one line. For more complicated code we can use a code block using “do” and “end”. It will yield the same results.

How about we look at one more example. Let’s say we have an array of strings.

In this example we have an array called “characters” populated with a few Mortal Kombat characters. We are mapping over this array and for each element in this array we are capitalizing all the letters with the .upcase method. Notice how within our pipes we have a variable called “string” which is representative of each element as it is passed in. We can really name this anything. However, a more appropriate name would have definitely been “character” since we are going through each “character in the “characters” array. If we run the above code we get the below:

(ignore the bundle exec ruby main.rb)

Conclusion

And there you have it! A fundamental tutorial on how to use .map in Ruby. Rule of thumb when ever you think “Transform” think of “.map”.

--

--

Responses (1)