Search code examples
rubyforeachiteratorruby-1.9.2

Is it possible to check to the position of an iterator in Ruby?


Is there a way to get the position of an iterator (how many times it has iterated)?

values = (1..100)
values.each do |value|
  if ... % 10 == 1 then puts iterator.count end
end

Or do you have to count explicitly:

values = (1..100)
counter = 0
values.each do |value|
  if counter % 10 == 1 then puts counter end
  counter += 1
end

Is there a cleaner approach?

Ruby 1.9.2


Solution

  • Use each_with_index

    values.each_with_index do |value, idx|
      puts idx if idx % 10 == 1
      # do something else
    end
    

    Or you can use a cooler alternative

    values.each.with_index do |value, idx|
      # work
    end
    

    I called it cooler because #with_index is relatively less known and it can be combined with map (and other methods) to yield interesting results.