Upg*_*ave 116 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)?
}
Run Code Online (Sandbox Code Playgroud)
YOU*_*YOU 286
如果您想知道可以使用的每次迭代的索引 .each_with_index
hash.each_with_index { |(key,value),index| ... }
Run Code Online (Sandbox Code Playgroud)
Kal*_*see 11
您可以迭代键,并手动获取值:
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
Run Code Online (Sandbox Code Playgroud)
编辑: per 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
Run Code Online (Sandbox Code Playgroud)