我有一个信息哈希,用于在广告工具中定位用户,如下所示:
{" geo_locations" => {"国家" => ["美国"," GB"," AR"]},"性别=> [1,2]}
因此,上述内容将针对这些国家/地区代码和所有性别中的所有用户。以上是哈希的简单版本。它可以包含更多具有自己的值数组的键。
我需要做的是在这个初始哈希的后面生成多个哈希值,这些哈希值贯穿哈希的所有可能组合。因此,在运行排列方法之后,上述哈希的预期输出将如下:
{" geo_locations" => {"国家" => ["美国"]},"性别=> [1] }
{" geo_locations" => {"国家" => [" GB"]},"性别=> [1] }
{" geo_locations" => {"国家" => [" AR"]},"性别=> [1] }
{" geo_locations" => {"国家" => ["美国"]},"性别=> [2] }
{" geo_locations" => {"国家" => [" GB"]},"性别=> [2] }
{" geo_locations" => {"国家" => [" AR"]},"性别=> [2] }
到目前为止,我已经尝试过各种各样的想法,例如遍历哈希并将每个键值提取到一个平面数组中,然后应用Array.product方法生成所有可能的排列,但到目前为止我还有一直在走向死胡同。笛卡尔积是否是上述的正确解决方案?可能还有另一种内置的ruby方法可以解决这个问题,我目前还没有意识到这一点!
答案 0 :(得分:1)
我会做
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]}]