Ruby each_with_index偏移量 [英] Ruby each_with_index offset

查看:107
本文介绍了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.

推荐答案

实际上, 枚举器#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

BTW,我认为它只存在于1.9.2。

BTW, I think it is there only in 1.9.2.

这篇关于Ruby each_with_index偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆