Possible to access the index in a Hash each loop?

RubyEnumerable

Ruby Problem Overview


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)?
}

Ruby Solutions


Solution 1 - Ruby

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

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

Solution 2 - Ruby

You could iterate over the keys, and get the values out manually:

hash.keys.each_with_index do |key, index|
   value = hash[key]
   print "key: #{key}, value: #{value}, index: #{index}\n"
   # use key, value and index as desired
end

EDIT: per rampion's comment, I also just learned you can get both the key and value as a tuple if you iterate over hash:

hash.each_with_index do |(key, value), index|
   print "key: #{key}, value: #{value}, index: #{index}\n"
   # use key, value and index as desired
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUpgradingdaveView Question on Stackoverflow
Solution 1 - RubyYOUView Answer on Stackoverflow
Solution 2 - RubyKaleb BraseeView Answer on Stackoverflow