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

后端 未结 4 1540
情歌与酒
情歌与酒 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:18

    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.

提交回复
热议问题