Can't all or most cases of `each` be replaced with `map`?

后端 未结 4 1542
情歌与酒
情歌与酒 2021-01-13 11:11

The difference between Enumerable#each and Enumerable#map is whether it returns the receiver or the mapped result. Getting back to the receiver is

4条回答
  •  无人及你
    2021-01-13 11:24

    I agree with what you said. Enumerable#each simply returns the original object it was called on while Enumerable#map sets the current element being iterated over to the return value of the block, and then returns a new object with those changes.

    Since Enumerable#each simply returns the original object itself, it can be very well preferred over the map when it comes to cases where you need to simply iterate or traverse over elements.

    In fact, Enumerable#each is a simple and universal way of doing a traditional iterating for loop, and each is much preferred over for loops in Ruby.

提交回复
热议问题