可以在哈希每个循环中访问索引吗?

发布于 2024-08-18 13:10:10 字数 269 浏览 7 评论 0原文

我可能遗漏了一些明显的东西,但是有没有办法访问哈希每个循环内迭代的索引/计数?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦萦几度 2024-08-25 13:10:10

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

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

If you like to know Index of each iteration you could use .each_with_index

hash.each_with_index { |(key,value),index| ... }
绅刃 2024-08-25 13:10: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

编辑:根据 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

You could iterate over the keys, and get the values out manually:

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

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:

hash.each_with_index do |(key, value), index|
   print "key: #{key}, value: #{value}, index: #{index}\n"
   # use key, value and index as desired
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文