Today I Learned

A Hashrocket project

Traverse mix of hashes and arrays in Ruby

If you have a hash or array with nested hashes and arrays, you can use dig and pass as an argument a mix of keys and indexes:

response = {
  data: {
    locations: [
      {
        name: "Jacksonville"
      }
    ]
  }
}

response.dig(:data, :locations, 0, :name)
=> "Jacksonville"
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.