I Dislike the each Method (and for Loops)

This article was automatically translated from Japanese by AI. Read the original Japanese version →

I dislike the each method (and for loops), so as much as possible I use map, select, and reduce (in Ruby terms).
The reason is to avoid obscuring the relationship between the collection passed in and the result of the operation.

To keep the explanation simple, let the input collection be xs and the returned collection be ys.

In the case of map, ys is a collection with the same number of elements as xs.
Each element of ys is expected to be determined by the corresponding element of xs, independent of the other elements.
If xs has an order, ys is expected to preserve that order.

In the case of select, each element of ys is equal to one of the elements of xs, and the number of elements in ys is less than or equal to xs.
Each element of ys is expected to be determined by a single element of xs, independent of the others (just like map).
If the input has an order, the return value is expected to preserve that order.

The return value of reduce is a single value.
Basically, the return value depends on the order of xs. If the operation satisfies the commutative law, then the return value does not depend on the order of the input.

A for loop or each statement does not make any of this explicit. That's why I dislike them.
Put the other way around, I use for loops or each when no return value is expected.
If you want to transform a collection while filtering it by a condition, you should call select first and then map.

max and sum belong to the reduce family. find is close to both select and reduce.