DEV Community

shiva kumar
shiva kumar

Posted on • Edited on

2 1

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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay