Ruby enumerable: map
This course covers Ruby's map method, which runs a block once per element and collects each result into a new array of the same length. It compares map with each, shows that map on a hash returns an array, and explains how to get a hash back with to_h or transform_values. Lessons also cover chaining map with uniq, compact and sort, transforming in place with map!, the collect alias, and common mistakes. A final challenge builds a small score normalizer.
What you'll learn
- ✓How map collects block results into a new array
- ✓Choosing between map and each by what happens to the block's result
- ✓Using map on hashes with to_h, and when to use transform_values
- ✓Chaining map with uniq, compact, sort and other array methods
- ✓When map! fits and why plain map is the safer default
- ✓The collect alias and common map pitfalls
map transforms every element
The last course set out each's job: run code once per element for its side effects, and hand back the same collection. map does the opposite job.
Read the full lesson free →Curriculum
7 lessonsmap transforms every element
map collects each block result into a new array of the same length and leaves the original untouched.
map vs each
Choose each for side effects and map for a new collection, based on what happens to the block's result.
map on hashes
map on a hash returns an array; get a hash back with to_h, or use transform_values.
Chaining map with other methods
Because map returns a plain array, methods like uniq, compact and sort chain onto it step by step.
map!: transforming in place
map! rewrites the original array in place, which changes a caller's array, so plain map is the safer default.
collect and common pitfalls
collect is an alias for map, and common mistakes include discarding the result, ending in puts, and expecting filtering.
Putting it together: a small challenge
A score normalizer combines map, to_h, compact and a guard clause, followed by an exercise to write it yourself.