【问题标题】:Possible to access the index in a Hash each loop?可以在每个循环的哈希中访问索引吗?
【发布时间】:2011-01-06 05:10:15
【问题描述】:

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

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)?
}

【问题讨论】:

  • 匿名:不,哈希没有排序。
  • 哈希在技术上没有排序,但在 ruby​​ 中你可以在某种意义上对它们进行排序。 sort() 会将它们转换为已排序的嵌套数组,然后您可以将其转换回散列:your_hash.sort.to_h

标签: ruby enumerable


【解决方案1】:

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

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

【讨论】:

  • 具体:hash.each_with_index { |(key,value),index| ... }
  • 括号是必要的 b/c hash.eachArray 中给出每个键值对。括号的作用与(key,value) = arr 相同,将第一个值(键)放入key,第二个放入value
  • 感谢@S.Mark,@rampion,这很有效。我没有在 RDoc for Hash 中看到 each_with_indexruby-doc.org/core/classes/Hash.html。现在我看到它是 Enumerable 的成员。但太糟糕了,RDoc 无法从 Hash.html 交叉引用 each_with_index
  • @Dave_Paroulek 我经常希望如此。在使用 vi 检查类的方法时,我发现手动检查父模块是必要的步骤。通常我只是跳到irb,然后使用ClassName#instance_methods 来确保我没有遗漏任何内容。
  • 谢谢,@rampion,ClassName#instance_methods 非常有帮助
【解决方案2】:

您可以遍历键,然后手动获取值:

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

【讨论】:

  • 拒绝从循环内部访问迭代集合和错误代码:第一个循环中的key 是一个键+值对数组,因此将其用作hash 中的索引是错误的。你测试过吗?
猜你喜欢
  • 1970-01-01
  • 2021-09-21
  • 2012-10-19
  • 2013-07-29
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多