Ruby 中 each.with_index 和 each_with_index 之间的区别? [英] difference between each.with_index and each_with_index in Ruby?
本文介绍了Ruby 中 each.with_index 和 each_with_index 之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我真的很困惑each.with_index
和each_with_index
之间的区别.它们有不同的类型,但在实践中似乎是相同的.
I'm really confused about the difference between each.with_index
and each_with_index
. They have different types but seem to be identical in practice.
推荐答案
with_index
方法采用一个可选参数来偏移起始索引.each_with_index
做同样的事情,但没有可选的起始索引.
The with_index
method takes an optional parameter to offset the starting index. each_with_index
does the same thing, but has no optional starting 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
这篇关于Ruby 中 each.with_index 和 each_with_index 之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文