The difference between Enumerable#each
and Enumerable#map
is whether it returns the receiver or the mapped result. Getting back to the receiver is trivial and you usually do not need to continue a method chain after each
like each{...}.another_method
(I probably have not seen such case. Even if you want to get back to the receiver, you can do that with tap
). So I think all or most cases where Enumerable#each
is used can be replaced by Enumerable#map
. Am I wrong? If I am right, what is the purpose of each
? Is map
slower than each
?
Edit:
I know that there is a common practice to use each
when you are not interested in the return value. I am not interested in whether such practice exists, but am interested in whether such practice makes sense other than from the point of view of convention.
Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.
map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)
You can pass as many iterable as you like to map() function in Python.
The map function takes two arguments: an iterable and a function , and applies the function to each element of the iterable. The return value is a map object ;).
The difference between map
and each
is more important than whether one returns a new array and the other doesn't. The important difference is in how they communicate your intent.
When you use each
, your code says "I'm doing something for each element." When you use map
, your code says "I'm creating a new array by transforming each element."
So while you could use map
in place of each
, performance notwithstanding, the code would now be lying about its intent to anyone reading it.
The choice between map
or each
should be decided by the desired end result: a new array or no new array. The result of map
can be huge and/or silly:
p ("aaaa".."zzzz").map{|word| puts word} #huge and useless array of nil's
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With