129

我可能遗漏了一些明显的东西,但是有没有办法在每个循环的哈希内访问迭代的索引/计数?

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

2 回答 2

321

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

hash.each_with_index { |(key,value),index| ... }
于 2010-01-18T02:38:49.927 回答
14

您可以遍历键,并手动获取值:

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

编辑:根据rampion的评论,我也刚刚了解到,如果您迭代,您可以将键和值作为一个元组获取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
于 2010-01-18T02:38:16.623 回答