DEV Community

shiva kumar
shiva kumar

Posted on • Updated on

Quick difference in ruby's Each vs Map vs Collect vs Select

Ruby iterators simply explained with an example

Each vs Map vs Collect vs Select

All of them iterators an array but the difference is on the return value

array = [1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

Below code prints 2,3,4,5 but returns original array

array.each do |a|
  puts a+1
end
2
3
4
5
=> [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Map and Collect have the same functionality with a different name. Iterates through each element and return a new array of elements returned by the block

array.collect {|a| a + 1}
=> [2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Select iterates and return new array of elements for which given block is true

 array.select  { |num|  num.even?  } 
[2, 4]
Enter fullscreen mode Exit fullscreen mode

Summary:

Each -> returns same array
Map & collect -> returns new array with code executed in block for each element
Select -> return new array for the which give block is true

In next post, we will look into more enumerable methods which are handy to know.

Top comments (0)