Question

I have a hash of information that is used to target users in an advertising tool which looks like the following:

{"geo_locations"=>{"countries"=>["US", "GB", "AR"]}, "genders =>[1, 2]}

So the above would target all users in those country codes and all genders. The above is a simple version of the hash. It could include many more keys with their own array of values too.

What I need to be able to do is generate multiple hashes off the back of this initial hash which run through all possible combinations of the hash. So the expected output from the above hash after running through a permutation method would be the following:

{"geo_locations"=>{"countries"=>["US"]}, "genders =>[1]}

{"geo_locations"=>{"countries"=>["GB"]}, "genders =>[1]}

{"geo_locations"=>{"countries"=>["AR"]}, "genders =>[1]}

{"geo_locations"=>{"countries"=>["US"]}, "genders =>[2]}

{"geo_locations"=>{"countries"=>["GB"]}, "genders =>[2]}

{"geo_locations"=>{"countries"=>["AR"]}, "genders =>[2]}

So far I've played around with various ideas such as walking through the hash and extracting each keys value into a flat array and then applying the Array.product method to generate all possible permutations but so far I have been hitting a dead end. Is the cartesian product even the correct solution for the above? There may well be another inbuilt ruby method to take care of this that I'm currently unaware of!

Was it helpful?

Solution

I'd do

hash = {"geo_locations"=>{"countries"=>["US", "GB", "AR"]}, "genders" =>[1, 2]}
countries = hash["geo_locations"]["countries"]
genders = hash['genders']

array_of_hashes = countries.product(genders).map do |val1,val2|
  {"geo_locations" => { "countries" => val1 }, "genders" => [val2] }
end
array_of_hashes
# => [{"geo_locations"=>{"countries"=>"US"}, "genders"=>[1]},
#     {"geo_locations"=>{"countries"=>"US"}, "genders"=>[2]},
#     {"geo_locations"=>{"countries"=>"GB"}, "genders"=>[1]},
#     {"geo_locations"=>{"countries"=>"GB"}, "genders"=>[2]},
#     {"geo_locations"=>{"countries"=>"AR"}, "genders"=>[1]},
#     {"geo_locations"=>{"countries"=>"AR"}, "genders"=>[2]}]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top