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

后端 未结 4 1541
情歌与酒
情歌与酒 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.

    0 讨论(0)
  • 2021-01-13 11:24

    The choice between map or each should be decided by the desired end result: a new array or no new array. The result of map can be huge and/or silly:

    p ("aaaa".."zzzz").map{|word| puts word} #huge and useless array of nil's
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题