What are the differences between "each", "foreach", "collect" and "map"?
enums, iteration, iterator, loops, ruby
Solution
`collect`/`map` are equivalent. They differ from `each` in that `each` only executes the block for each element, whereas `collect`/`map` return an array with the results of calling the block for each element. Another way to put it might be, `each` is expected to do something with each element, whereas `map` is expected to transform each element (map it onto something else).
You could use `collect` or `map` anywhere `each` is used, and your code will still work. But it will probably be slightly less efficient because it collects the results in an array, unless your Ruby implementation realizes it doesn't have to bother creating an array because it's never used.
Another reason to use `each` instead of `map` or `collect` is to help out anyone reading your code. If I see `each` then I can be like okay, we're about to use each element of the data to do something. If I see `map` then I'm expecting to see new data being created, based on a remapping of the old data.
With regards to `map` vs. `collect` I would say it's a matter of preference, but you should pick one and stick with it for consistency.
Problem
It seems like there are a lot of ways to loop over an Enumerable in Ruby. Are there any differences between `each`, `foreach`, or in `collect`, `map` or other similar methods? Or is there a reason I shouldn't use certain methods in certain situations?