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

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

    You can see the significant difference between map and each when you're composing these enumaratiors.

    For example you need to get new array with indixes in it:

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

    Or for example you just need to apply some method to all elements in array and print result without changing the original array:

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

    And there's a plenty another examples where the difference between each and map is important key in the writing code in functional style.

提交回复
热议问题