hero-background-image-header

Tips for Using the Ruby Map Method

By Flatiron SchoolOctober 18, 2012

The following is a guest post by Ericka Ward and originally appeared on her blog. Ericka is currently a student a The Flatiron School.

I’m now in my first month of learning Ruby. Lately, I’ve been having some fun learning about the map method. I first came across the map method while using the related each method to iterate over an array. I wanted to use the each method to create a new array and my wonderful teacher Avi explained that I should be using map instead.

Blog post image: tumblr_mc3xz4uRMC1rtan47.png

Each vs Map

Each statements return the original input. Each is about iteration, it’s not best to use when you are interested in collecting data. Map is similar to each but can collect the data and has a meaningful return value. The return value will be the altered array, while the return value for each is just the original array you passed it. Whenever you notice that you are using each and then pushing the output into an array, you should use map instead.

Map returns a modified array of the original that is passed to it.

Blog post image: tumblr_mc3xznf7lX1rtan47.png

Print (and also puts) always returns nil and shouldn’t be used in map

Blog post image: tumblr_mc3xzvw9xA1rtan47.png

For the example above, it will add the ! to the name, print that value, and since print returns nil, it will add nil to the new array. So at the end of the operation, we will have an array of all nils where we were expecting to get names.

You shouldn’t use return in blocks

Return interrupts (breaks) a method. If you use return, you will get an error message.

Blog post image: tumblr_mc3y0bf4p21rtan47.png

Brackets vs Do…End

Use curly braces for one line or when there is a return value and you want to chain methods. If your map statement is more than one line and you aren’t chaining methods, it’s probably more clear to use do & end. Let’s try to rewrite the map statement above to use do & end:

Blog post image: tumblr_mc3y0vIjco1rtan47.png

As you can see, with this code, it is much more clear with the braces rather than the do & end. Choosing to use the curly braces or do & end is a matter of the specific situation.

Headshot of Flatiron School

Flatiron School

Blog Post Author

All Articles by Flatiron School