【问题标题】:difference between each.with_index and each_with_index in Ruby?Ruby 中 each.with_index 和 each_with_index 的区别?
【发布时间】:2015-05-15 02:35:10
【问题描述】:

我真的很困惑each.with_indexeach_with_index 之间的区别。它们有不同的类型,但在实践中似乎是相同的。

【问题讨论】:

    标签: ruby


    【解决方案1】:

    with_index 方法采用可选参数来偏移起始索引。 each_with_index 做同样的事情,但没有可选的起始索引。

    例如:

    [:foo, :bar, :baz].each.with_index(2) do |value, index|
        puts "#{index}: #{value}"
    end
    
    [:foo, :bar, :baz].each_with_index do |value, index|
        puts "#{index}: #{value}"
    end
    

    输出:

    2: foo
    3: bar
    4: baz
    
    0: foo
    1: bar
    2: baz
    

    【讨论】:

      【解决方案2】:

      each_with_index 早先被引入到 Ruby 中。 with_index稍后介绍:

      1. 允许更广泛地与各种枚举器一起使用。
      2. 允许索引从0以外的数字开始。

      今天,从通用性和可读性的角度来看,使用with_index会更好,但从加速代码的角度来看,each_with_index的运行速度略快于each.with_index

      当你觉得单个方法可以很容易地通过几个方法的直接链接来表达时,通常情况下单个方法比链接要快。至于另一个例子,reverse_each 的运行速度比reverse.each 快。这些方法有存在的理由。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-23
        • 2011-08-04
        • 2015-05-08
        • 2011-10-12
        • 2016-01-31
        • 2012-05-25
        • 1970-01-01
        相关资源
        最近更新 更多