I have a complex data structure that looks as follows:
ds1 =
{
'item1' =>
{
'value' => '1024',
'flavor' => %w(s m l xl),
'platform_version' => %w(7),
},
'item2' =>
[{
'value' => '2000000',
'flavor' => %w(l xl),
'platform_version' => %w(7),
},
{
'value' => '1000000',
'flavor' => %w(s m),
'platform_version' => %w(6),
},],
}
I'm currently looping over this as follows:
ds1.each do |name, obj|
if obj.is_a?(Array)
# Found that the data structure has multiple scenarios for the same key and need to loop over each element
obj.each do |sub_obj|
next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
obj_func(name, sub_obj) # call a function here
end
else
# hash only has one element so treat normally, no need for another loop
next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
obj_func(name, sub_obj) # call a function here
end
end
Sometimes I have much more code that I need to execute and having to repeat it twice depending on whether the "obj" is an array or not just makes my code look busy/ugly. Is there a more elegant way to handle this?