You Don't Need to Count Array Offsets by Hand

October 02, 2009

When you need both the item and its index while iterating over an array in Ruby, don't do this:

index = 0
for item in array
  index += 1
  puts "Item #{index}: #{item.inspect}"
end

Do this instead:

array.each_with_index do |item, index|
  puts "Item #{index}: #{item.inspect}"
end

Ruby's Enumerable module is full of handy methods like this. Take a few minutes to read through the documentation — your code will be better for it.

Questions or thoughts? Get in touch.