Iterating over a Ruby Hash while tracking the loop index

Updated . Posted . Visible to the public.

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
Last edit
Michael Leimstädtner
Keywords
step
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2014-07-30 08:07)