views:

168

answers:

1

I have an object of type Hash that I want to loop over via hash.each do |key, value|. I would like to get the number of times I've been through the loop starting at 1.

Is there a method similar to each that provides this (while still providing the hash key/value data), or do I need to create another counter variable to increment within the loop?

+9  A: 

Use each_with_index instead of each. Note: the index does start at 0:

hash.each_with_index do |(key, value), index|
Marc-André Lafortune
Awesome, thanks!
Matt Huggins