¿Es posible acceder al índice en un Hash cada bucle?


Probablemente me falta algo obvio, pero ¿hay una manera de acceder al índice/recuento de la iteración dentro de un hash cada bucle?

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)?
}
Author: Andrew Grimm, 2010-01-18

2 answers

Si quieres saber el Índice de cada iteración puedes usar .each_with_index

hash.each_with_index { |(key,value),index| ... }
 259
Author: YOU,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-24 07:13:17

Puede iterar sobre las claves y obtener los 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: según el comentario de rampion, también acabo de aprender que puedes obtener tanto la clave como el valor como una tupla si iteras sobre 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
 10
Author: Kaleb Brasee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-18 02:45:47