Read more

Iterate over any enumerable with an index

Thomas Klemm
October 13, 2014Software engineer

tl;dr: Use with_index


ActiveRecord's find_each with index

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

If you do not provide a block to find_each, it will return an Enumerator Show archive.org snapshot for chaining with other methods:

Person.find_each.with_index do |person, index|
  person.award_trophy(index + 1)
end

Ruby's map with index

Similarly, you may need an index when using other methods, like map, flat_map, detect (when you need the index for detection), or similar. Here is an example for map:

people.map.with_index do |person, index|
  person.at_rank(index + 1)
end
Posted by Thomas Klemm to makandra dev (2014-10-13 15:00)