You don't need to count array offsets by hand!

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
02 Oct 2009

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.

My opinions are my own and my employer can't have them.