可能访问哈希每个循环中的索引?

我可能错过了一些明显的东西,但是有没有一种方法可以访问每个循环中散列内部迭代的索引/计数?

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

如果你想知道每个迭代的索引,你可以使用.each_with_index

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

您可以迭代键,手动获取值:

 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 

编辑:每斜坡的评论,我也刚刚了解到,如果你迭代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