How to Use the Map Method in Ruby

Lorraine Nabua
2 min readApr 19, 2021

This blog is for beginner coders who are learning Ruby.

The main use for the Map method in Ruby is to efficiently transform data. The Map method can be used with Arrays, Hashes, and Ranges. Below are some examples of how to use Map.

Using Map with arrays:

Within the curly braces is our block code. |n| represents each element in the array and each element will be multiplied by four. Map will transform the original array based on this block code and return a new array. The original array, however, will not be altered. Another name for Map is Collect. You can use either one but most programming languages use Map, therefore, it’s best to use Map.

Difference between Map and Each:

Map will collect the result based on running the code block over the elements of the array. Each is a very basic method that just runs the code block over the elements without collecting the values.

Using Map with hashes:

When using Map with hashes, we need two variables. |k, v| are the two variables which represent the keys and values, respectively. In the example above, “name” and “hobby” are the keys, and “Lorraine” and “hiking” are the values. The result of the first Map method gives us the sizes of the values which in this case is the character length of the values. Map will always return an array even if what you started with was a hash or any other kind of object that supports the Map method. The result of using the map method is always going to be an array.

The second Map method in the example above returns a hash instead of an array. [k, v.size] in the code block will give us an array of arrays or a multi-dimensional array. The to_h or To Hash method will transform the multi-dimensional array into a hash. The new hash will contain new values which will now be the size of the previous string values.

Conclusion

Now you’ve learned how the Map method works with arrays and hashes. You’ve also learned the difference between Map and Each, and the alias for Map which is Collect. Try to practice using Map with other objects and methods.

--

--