代码之家  ›  专栏  ›  技术社区  ›  Upgradingdave

可以访问散列循环中的索引吗?

  •  113
  • Upgradingdave  · 技术社区  · 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)?
    }
    
    2 回复  |  直到 13 年前
        1
  •  314
  •   Michael Shimmins    13 年前

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

    hash.each_with_index { |(key,value),index| ... }
    
        2
  •  12
  •   Kaleb Brasee    15 年前

    您可以迭代键,并手动获取值:

    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