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

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)

  • 具体来说:`hash.each_with_index {|(key,value),index | ......}` (24认同)
  • parens是必要的b/c`hash.each`给出'Array`中的每个键值对.parens与`(key,value)= arr`做同样的事情,将第一个值(键)放入`key`,第二个值放入`value`. (22认同)
  • @Dave_Paroulek我经常也希望如此.我发现在使用vi检查类的方法时,手动检查父模块是必要的步骤.通常我只是跳到`irb`,并使用`ClassName #instance_methods`来确保我没有错过任何东西. (2认同)

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)