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
`
CodePudding user response:
Assuming you have the company_tree
variable like described in your question, you can use recursion to iterate over each element and all of its subs. This is the code I made and I will explain it a bit further below
def destruct_tree(element)
puts "#{element[:label]} with subs #{element[:subs]}"
element[:subs].each do |sub|
destruct_tree sub
end
end
destruct_tree company_tree
You give the function the company_tree
element. Then it prints its label and subs. Then it iterates over all the subs and passes them to the same function again. Which will intern print their label and subs and run through all their subs again.
I hope this made sense
CodePudding user response:
You can iterate through the hash like below:
def iterate_through(company_tree)
puts "#{company_tree[:label]} => #{company_tree[:subs]}"
company_tree[:subs].each do |sub|
iterate_through(sub)
end
end
iterate_through(company_tree)
Output:
Autos => [{: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=>[]}]
SUVs => []
Trucks => [{:label=>"2 Wheel Drive", :subs=>[]}, {:label=>"4 Wheel Drive", :subs=>[{:label=>"Ford", :subs=>[]}, {:label=>"Chevrolet", :subs=>[]}]}]
2 Wheel Drive => []
4 Wheel Drive => [{:label=>"Ford", :subs=>[]}, {:label=>"Chevrolet", :subs=>[]}]
Ford => []
Chevrolet => []
Sedan => []