gpt4 book ai didi

ruby each_with_index 偏移量

转载 作者:数据小太阳 更新时间:2023-10-29 06:18:50 35 4
gpt4 key购买 nike

我可以在 each_with_index 循环迭代器中定义索引的偏移量吗?我的直接尝试失败了:

some_array.each_with_index{|item, index = 1| some_func(item, index) }

编辑:

澄清:我不想要数组偏移我希望 each_with_index 中的索引不是从 0 开始,而是例如1.

最佳答案

实际上,Enumerator#with_index接收偏移量作为可选参数:

[: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 中。

关于 ruby each_with_index 偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5646390/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com