Ruby:在each、map、inject、each_with_index 和each_with_object之间进行选择

2024-04-15

许多年前,当我开始编写 Ruby 时,我花了一段时间才理解each https://ruby-doc.org/core-2.2.0/Array.html#method-i-each and map https://ruby-doc.org/core-2.3.1/Enumerable.html#method-i-map。当我发现所有其他的事情时,情况只会变得更糟可枚举 https://ruby-doc.org/core-2.3.1/Enumerable.html and Array https://ruby-doc.org/core-2.2.0/Array.html方法。

借助官方文档和many https://stackoverflow.com/questions/5254128/arrayeach-vs-arraymap 堆栈溢出 https://stackoverflow.com/questions/5347949/whats-different-between-each-and-collect-method-in-ruby 问题 https://stackoverflow.com/questions/3294509/for-vs-each-in-ruby,我慢慢开始明白那些方法是做什么的。

但这是我花了更长的时间才理解的:

  • 为什么我应该使用一种或另一种方法?
  • 有什么指导方针吗?

我希望这个问题不是重复的:我对“为什么?”更感兴趣。比“什么?”或者“如何?”,我认为这可以帮助 Ruby 新手。


A more tl;dr answer:

如何在each、map、inject、each_with_index 和each_with_object 之间进行选择?

  • Use #each当你想要的时候“通用的”迭代并且不关心结果。示例 - 您有数字,您想要打印每个数字的绝对值:

    numbers.each { |number| puts number.abs }
    
  • Use #map当您想要一个新列表时,其中每个元素都是通过转换原始元素以某种方式形成的。示例 - 你有数字,你想得到它们的平方:

    numbers.map { |number| number ** 2 }
    
  • Use #inject当您想以某种方式将整个列表减少为一个值时。示例 - 你有数字,你想得到它们的总和:

    numbers.inject(&:+)
    
  • Use #each_with_index在同样的情况下#each,除非您还需要每个元素的索引:

    numbers.each_with_index { |number, index| puts "Number #{number} is on #{index} position" }
    
  • 用于#each_with_object都比较有限。最常见的情况是如果您需要类似的东西#inject,但想要一个新的集合(而不是奇异值),它不是原始集合的直接映射。示例 - 数字直方图(频率):

    numbers.each_with_object({}) { |number, histogram| histogram[number] = histogram[number].to_i.next }
    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ruby:在each、map、inject、each_with_index 和each_with_object之间进行选择 的相关文章

随机推荐