可以访问 Hash each 循环中的索引吗?

我可能遗漏了一些显而易见的东西,但是有没有一种方法可以在 hash each 循环中访问迭代的索引/计数?

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)?
}
74366 次浏览

您可以对键进行迭代,然后手动获取值:

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

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

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