我可能遗漏了一些明显的东西,但有没有办法在每个循环中访问散列内的迭代索引/计数?
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)?
}
答案 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