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 Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)