Hash Issue when looping through

So I have been struggling with an issue for a while now and seem to be
getting nowhere…

The problem exists while I am looping through a hash, around the 3rd
level
deep.

So my code looks a little like:

request[:items][:location_item].each do |locaton_item|
pp location_item[:name]
location_item[:items][:sub_area_option_item].each do
|sub_area_option_item|
pp sub_area_option_item[:name]
sub_area_option_item[:items][:option_item].each do |option_item|
option_item[:name] <- THIS IS WHERE MY CODE BREAKS
end
end
end

The reason this is failing is because this particular part of the loop
has
2 different variants, one where there is an infinite amount of
“option_items” and one where there is only one “option_item”. Instead of
sending me back the single “option_item” it is looping through this
“option_item” and not finding this particular field. Any ideas as how to
force it when only one object is found to still return it as an array?

This is solved! By adding flatten to the last loop…

sub_area_option_item[:items][:option_item].flatten.each do 

|option_item|
option_item[:name] <- THIS IS WHERE MY CODE BREAKS
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs