Ruby each_with_index 偏移量 [英] Ruby each_with_index offset
本文介绍了Ruby each_with_index 偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以在 each_with_index 循环迭代器中定义索引的偏移量吗?我的直接尝试失败了:
Can I define the offset of the index in the each_with_index loop iterator? My straight forward attempt failed:
some_array.each_with_index{|item, index = 1| some_func(item, index) }
澄清:我不想要数组偏移量,我希望 each_with_index 中的索引不是从 0 开始,而是例如1.
Clarification: I don't want an array offset I want that the index within the each_with_index doesn't start from 0 but e.g. 1.
推荐答案
其实Enumerator#with_index
接收偏移量作为可选参数:
Actually, Enumerator#with_index
receives offset as an optional parameter:
[:foo, :bar, :baz].to_enum.with_index(1).each do |elem, i|
puts "#{i}: #{elem}"
end
输出:
1: foo
2: bar
3: baz
顺便说一句,我认为它只存在于 1.9.2 中.
BTW, I think it is there only in 1.9.2.
这篇关于Ruby each_with_index 偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文