This is common question for Ruby on Rails developer(Beginner). Map and Collect both are looping methods used on Array, Hash etc. This tutorial will help understanding the exact difference between these two methods.
Let’s create sample array for the demo,
Now that array a has been created. Let’s perform collect and map operation on array a.
Collect vs Map
- collect and map methods are one and the same considering their implementation.
C level implementation of these methods explains how these methods are same.
Thus, we will see what collect/map does operations on Array below
Collect/Map in Action
- Returns Array evaluation condition/statement passed as code block passed to the method
- Internally these methods each on the array passed and evaluates code block and creates new array satisfying the condition.
- The new array is finally returned as the result.
For array a created above,
The above invocation of collect and map methods will return array. Thus, b and c are Arrays.
If we see the output produced by Ruby Interpreter then, it is clear that b and c have same array value.
- In Ruby difference between collect and map does not exist.
- C level implementation of these methods shows that they both are same. Collect is an alias to Map