Ruby : Choosing between each, map, inject, each_with_index and each_with_object

前端 未结 2 1051
攒了一身酷
攒了一身酷 2021-02-07 15:30

When I started writing Ruby many years ago, it took me a while to understand the difference between each and map. It only got worse when I discovered all the other Enumerable an

2条回答
  •  忘了有多久
    2021-02-07 16:12

    A more tl;dr answer:

    How to choose between each, map, inject, each_with_index and each_with_object?

    • Use #each when you want "generic" iteration and don't care about the result. Example - you have numbers, you want to print the absolute value of each individual number:

      numbers.each { |number| puts number.abs }
      
    • Use #map when you want a new list, where each element is somehow formed by transforming the original elements. Example - you have numbers, you want to get their squares:

      numbers.map { |number| number ** 2 }
      
    • Use #inject when you want to somehow reduce the entire list to one single value. Example - you have numbers, you want to get their sum:

      numbers.inject(&:+)
      
    • Use #each_with_index in the same situation as #each, except you also want the index with each element:

      numbers.each_with_index { |number, index| puts "Number #{number} is on #{index} position" }
      
    • Uses for #each_with_object are more limited. The most common case is if you need something similar to #inject, but want a new collection (as opposed to singular value), which is not a direct mapping of the original. Example - number histogram (frequencies):

      numbers.each_with_object({}) { |number, histogram| histogram[number] = histogram[number].to_i.next }
      

提交回复
热议问题