Ruby each_with_index offset

Mark picture Mark · Apr 13, 2011 · Viewed 74.3k times · Source

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) }

Edit:

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.

Answer

Mladen Jablanović picture Mladen Jablanović · Apr 13, 2011

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.