可以在哈希每个循环中访问索引吗?
我可能遗漏了一些明显的东西,但是有没有办法访问哈希每个循环内迭代的索引/计数?
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)?
}
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)?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想知道每次迭代的索引,您可以使用
.each_with_index
If you like to know Index of each iteration you could use
.each_with_index
您可以迭代键,并手动获取值:
编辑:根据 Rampion 的评论,我还刚刚了解到,如果您迭代
hash,则可以将键和值作为元组获取:
You could iterate over the keys, and get the values out manually:
EDIT: per rampion's comment, I also just learned you can get both the key and value as a tuple if you iterate over
hash
: