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| s
offset = 2
some_array[offset..-1].each_with_index{|item, index| some_func(item, index+offset) }
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
outputs:
1: foo
2: bar
3: baz
BTW, I think it is there only in 1.9.2.
I ran into it.
My solution not necessary is the best, but it just worked for me.
In the view iteration:
just add: index + 1
That's all for me, as I don't use any reference to those index numbers but just for show in a list.
This works in every ruby version:
%W(one two three).zip(1..3).each do |value, index|
puts value, index
end
And for a generic array:
a.zip(1..a.length.each do |value, index|
puts value, index
end
The following is succinct, using Ruby's Enumerator class.
[:foo, :bar, :baz].each.with_index(1) do |elem, i|
puts "#{i}: #{elem}"
end
output
1: foo
2: bar
3: baz
Array#each returns an enumerator, and calling Enumerator#with_index returns another enumerator, to which a block is passed.
Ariel is right. This is the best way to handle this, and it's not that bad
ary.each_with_index do |a, i|
puts i + 1
#other code
end
That is perfectly acceptable, and better than most of the solutions I've seen for this. I always thought this was what #inject was for...oh well.