Pergunta

Provavelmente estou perdendo algo óbvio, mas existe uma maneira de acessar o índice/contagem da iteração dentro de um hash a cada 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)?
}
Foi útil?

Solução

Se você gosta de saber o índice de cada iteração que você poderia usar .each_with_index

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

Outras dicas

Você pode iterar sobre as chaves e obter os valores manualmente:

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

EDITAR: Por comentário de Rampion, eu também aprendi que você pode obter a chave e o valor como uma tupla se você itera 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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top