Tips for Using the Ruby Map Method
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 […]
Reading Time 1 min
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.
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.
Print (and also puts) always returns nil and shouldn’t be used in map
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.
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:
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.
Posted by Flatiron School / October 18, 2012
Learn to Code Python: Free Lesson for Beginners
Sabrina Hernandez: From Dental Tech to UX / UI Product Designer
After 7 years as a dental tech, Sabrina Hernandez was ready for a change. She enrolled in Flatiron School and has since pivoted into a career in UX / UI Product Design.