Each vs map vs collect
Have you got a headache with choosing the right method and how to use it in our code?
Not anymore! I will explain you step by step how to use each of them and show the difference. Let’s start!
For sure, you already know that Array and Hash have their own methods for adding, deleting or accessing data. They can implement their own version of the each method to iterate over their items. But for sure we would like to see some magic! Let’s use Enumerable methods to make them really powerful.
Each
The method each is the most flexible method, but on another hand, it's also the least expressive. That means that another programmer who will read your code don’t know what the method is doing straight away. The programmer needs to analyse your code.
When you aren't sure which way to go, you might want to use it, but most of the time you really want to use another method like map, collect, find or other Enumerable methods. Rember that enumerable methods have been built based on method each.
Maybe in the future, you would like to write the method what is not covering by Enumerable. So using each helps you to create your own methods.
numbers = [1, 3, 5, 7]
numbers.each { |n| puts 2*n }
return [1,3,5,7]
Map
Difference between each and map is the map returns changed array when each always returns the original unchanged object. Let think of the map as a better version of the each.
numbers = [1, 3, 5, 7]
numbers.each { |n| puts 2*n }
return [2,6,10,14]
Collect
Collect method is doing the same thing as a map.
Happy coding!