Search code examples
ruby-on-railsrubyiterationnested-loopstraversal

Iterate through deep nested hash by using Ruby on Rails


I'm trying to iterate through a nested object to retrieve a specific object identified by a string. In the sample object below, the identifier string is the "label" property. I don't know how to iterate down through the tree to return the appropriate object.

My Ruby and Rails versions are pretty old. Ruby - 1.9.3 Rails - 3.0.9

`

company_tree = {
  label: 'Autos',
  subs: [
    {
      label: 'SUVs',
      subs: []
    },
    {
      label: 'Trucks',
      subs: [
        {
          label: '2 Wheel Drive',
          subs: []
        },
        {
          label: '4 Wheel Drive',
          subs: [
            {
              label: 'Ford',
              subs: []
            },
            {
              label: 'Chevrolet',
              subs: []
            }
          ]
        }
      ]
    },
    {
      label: 'Sedan',
      subs: []
    }
  ]
}

`

I tried using below code. But I didn't worked. It only return the second array only. It won't go beyond that.

`

data = JSON.parse(requestData)

data['company_tree']['subs'].each do |element|
    puts "element=> #{element['subs']}"
end

`


Solution

  • Thanks for the support, I found out the solution

        def iterate(i)
            if i.is_a?(Hash)
                i.each do |k, v|
                    if v.is_a?(Hash) || v.is_a?(Array)
                        iterate(v)
                    else
                        puts("k is #{k}, value is #{v}")
                    end
                end
            end
            if i.is_a?(Array)
                i.each do |v|
                    iterate(v)
                end
            end
        end