【发布时间】:2015-05-15 02:35:10
【问题描述】:
我真的很困惑each.with_index 和each_with_index 之间的区别。它们有不同的类型,但在实践中似乎是相同的。
【问题讨论】:
标签: ruby
我真的很困惑each.with_index 和each_with_index 之间的区别。它们有不同的类型,但在实践中似乎是相同的。
【问题讨论】:
标签: ruby
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
【讨论】:
each_with_index 早先被引入到 Ruby 中。 with_index稍后介绍:
0以外的数字开始。今天,从通用性和可读性的角度来看,使用with_index会更好,但从加速代码的角度来看,each_with_index的运行速度略快于each.with_index。
当你觉得单个方法可以很容易地通过几个方法的直接链接来表达时,通常情况下单个方法比链接要快。至于另一个例子,reverse_each 的运行速度比reverse.each 快。这些方法有存在的理由。
【讨论】: