Working with arrays 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

There are a bunch of handy methods like this. Read the Enumerable documentation and make your code that little bit more readable.

written by
Craig
published
2009-10-02
Disagree? Found a typo? Got a question?
If you'd like to have a conversation about this post, email craig@barkingiguana.com. I don't bite.
You can verify that I've written this post by following the verification instructions:
curl -LO http://barkingiguana.com/2009/10/02/you-dont-need-to-count-array-offsets-by-hand.html.orig
curl -LO http://barkingiguana.com/2009/10/02/you-dont-need-to-count-array-offsets-by-hand.html.orig.asc
gpg --verify you-dont-need-to-count-array-offsets-by-hand.html.orig{.asc,}