可以在哈希每个循环中访问索引吗?

时间:2010-01-18 02:23:46

标签: ruby enumerable

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

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

2 个答案:

答案 0 :(得分:280)

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

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

答案 1 :(得分:10)

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

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