Impossible to replace all or most cases of "each" with a "card"?

The difference between Enumerable#eachand Enumerable#mapis whether it returns a receiver or a matching result. Returning to the receiver is trivial, and you usually do not need to continue the method chain after eachhow each{...}.another_method(I probably haven’t seen such a case. Even if you want to return to the receiver, you can do this with tap). Therefore, I think that all or most of the cases when used Enumerable#eachcan be replaced by Enumerable#map. Am I mistaken? If I am right, what is the purpose each? Is mapslower than each?

Edit : I know that there is a common usage practice eachwhen you are not interested in the return value. I am not interested in whether such a practice exists, but I am interested in whether such a practice makes sense, except from the point of view of the convention.

+5
source share
4 answers

The choice between mapor eachshould be determined by the desired end result: a new array or without a new array. The result mapcan be huge and / or stupid:

p ("aaaa".."zzzz").map{|word| puts word} #huge and useless array of nil's
+5
source

The difference between mapand is eachmore important than returning a new array, while the other is not. The important difference is how they communicate your intentions.

each, " - ". map, " , ".

, map each, , , .

+6

, . Enumerable#each , , Enumerable#map , , .

Enumerable#each , map, , .

, Enumerable#each , Ruby.

+2

map each, enumaratiors.

, :

array.each.with_index.map { |index, element| [index, element] }

, , :

m = 2.method(:+)

[1,2,3].each { |a| puts m.call(a) } #=> prints 3, 4, 5

, each map .

0

All Articles