Ruby 中 each.with_index 和 each_with_index 之间的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20258086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
difference between each.with_index and each_with_index in Ruby?
提问by Stan
I'm really confused about the difference between each.with_indexand each_with_index. They have different types but seem to be identical in practice.
我真的很困惑each.with_index和之间的区别each_with_index。它们有不同的类型,但在实践中似乎是相同的。
回答by blacktide
The with_indexmethod takes an optional parameter to offset the starting index. each_with_indexdoes the same thing, but has no optional starting index.
该with_index方法采用一个可选参数来偏移起始索引。each_with_index做同样的事情,但没有可选的起始索引。
For example:
例如:
[: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
Outputs:
输出:
2: foo
3: bar
4: baz
0: foo
1: bar
2: baz
回答by sawa
each_with_indexwas introduced into Ruby earlier. with_indexwas introduced later:
each_with_index早先被引入Ruby。with_index后来介绍:
- to allow wider usage with various enumerators.
- to allow index to start from a number other than
0.
- 允许更广泛地使用各种枚举器。
- 允许索引从
0.以外的数字开始。
Today, using with_indexwould be better from the point of view of generality and readability, but from the point of view of speeding up the code, each_with_indexruns slightly faster than each.with_index.
今天,with_index从通用性和可读性的角度来看,使用会更好,但从加速代码的角度来看,each_with_index运行速度比each.with_index.
When you feel that a single method can be easily expressed by straightforward chaining of a few methods, it is usually the case that the single method is faster than the chain. As for another example of this, reverse_eachruns faster than reverse.each. These methods have reason to exist.
当你觉得一个方法可以很容易地通过几个方法的直接链接来表达时,通常情况下是单个方法比链更快。至于另一个例子,reverse_each运行速度比reverse.each. 这些方法有存在的理由。

