可以在每个循环的哈希中访问索引吗? [英] Possible to access the index in a Hash each loop?
本文介绍了可以在每个循环的哈希中访问索引吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可能遗漏了一些明显的东西,但是有没有办法在每个循环的哈希中访问迭代的索引/计数?
I'm probably missing something obvious, but is there a way to access the index/count of the iteration inside a hash each loop?
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)?
}
推荐答案
如果你想知道每次迭代的索引,你可以使用 .each_with_index
If you like to know Index of each iteration you could use .each_with_index
hash.each_with_index { |(key,value),index| ... }
这篇关于可以在每个循环的哈希中访问索引吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文