Possible to access the index in a Hash each loop?

Upgradingdave picture Upgradingdave · Jan 18, 2010 · Viewed 65.2k times · Source

I'm probably missing something obvious, but is there a way to access the index/count of the iteration inside a hash each loop?

hash = {'three' => 'one', 'four' => 'two', 'one' => 'three'}
hash.each { |key, value| 
    # any way to know which iteration this is
    #   (without having to create a count variable)?
}

Answer

YOU picture YOU · Jan 18, 2010

If you like to know Index of each iteration you could use .each_with_index

hash.each_with_index { |(key,value),index| ... }