/ RAILS

Ruby difference between collect and map

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,

a = [1,2,31,4,7,9,21]
=> [1, 2, 31, 4, 7, 9, 21]

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.

    Refer source of collect and map on APIDock. i.e. Collect is alias to Map method.

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.

Example,

For array a created above,

b = a.collect{|x| x.even?}
=> [false, true, false, true, false, false, false]

c = a.map{|x| x.even?}
=> [false, true, false, true, false, false, false]

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.

Conclusion

  • 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
akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee