Iterating over a Ruby Hash while tracking the loop index

You know each_with_index from arrays:

    ['hello', 'universe'].each_with_index do |value, index|
      puts "#{index}: #{value}"
    end
    # 0: hello
    # 1: universe

This also works on hashes. However, mind the required syntax:

    { hello: 'universe', foo: 'bar' }.each_with_index do |(key, value), index|
      puts "#{index}: #{key} => #{value}"
    end
    # 0: hello => universe
    # 1: foo => bar

The reason is that each_with_index yields 2 elements to the block, and you need to deconstruct the first element (a tuple of key and value) explicitly.

Note that Hashes are ordered since Ruby 1.9 but not on older Rubies.

Arne Hartherz