Possible to access the index in a Hash each loop?

后端 未结 2 1362
悲哀的现实
悲哀的现实 2021-01-30 02:35

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\',          


        
相关标签:
2条回答
  • 2021-01-30 03:11

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

    hash.each_with_index { |(key,value),index| ... }
    
    0 讨论(0)
  • 2021-01-30 03:12

    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
    
    0 讨论(0)
提交回复
热议问题