Read more

Iterating over a Ruby Hash while tracking the loop index

Arne Hartherz
July 30, 2014Software engineer at makandra GmbH

You know each_with_index from arrays:

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

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2014-07-30 10:07)