dva*_*erb 6 ruby arrays hash combinations ruby-on-rails
对于电子商务应用程序,我试图将一个选项的哈希值转换为表示这些选择组合的哈希数组.例如:
# Input:
{ :color => [ "blue", "grey" ],
:size => [ "s", "m", "l" ] }
# Output:
[ { :color => "blue", :size => "s" },
{ :color => "blue", :size => "m" },
{ :color => "blue", :size => "m" },
{ :color => "grey", :size => "s" },
{ :color => "grey", :size => "m" },
{ :color => "grey", :size => "m" } ]
Run Code Online (Sandbox Code Playgroud)
输入内部可能有其他选项,每个选项的选项数量不确定,但它只能嵌套1级深度.任何
以上变体:
input = { color: [ "blue", "grey" ],
size: [ "s", "m", "l" ],
wt: [:light, :heavy] }
keys = input.keys
#=> [:color, :size, :wt]
values = input.values
#=> [["blue", "grey"], ["s", "m", "l"], [:light, :heavy]]
values.shift.product(*values).map { |v| Hash[keys.zip(v)] }
#=> [{:color=>"blue", :size=>"s", :wt=>:light},
# {:color=>"blue", :size=>"s", :wt=>:heavy},
# {:color=>"blue", :size=>"m", :wt=>:light},
# {:color=>"blue", :size=>"m", :wt=>:heavy},
# {:color=>"blue", :size=>"l", :wt=>:light},
# {:color=>"blue", :size=>"l", :wt=>:heavy},
# {:color=>"grey", :size=>"s", :wt=>:light},
# {:color=>"grey", :size=>"s", :wt=>:heavy},
# {:color=>"grey", :size=>"m", :wt=>:light},
# {:color=>"grey", :size=>"m", :wt=>:heavy},
# {:color=>"grey", :size=>"l", :wt=>:light},
# {:color=>"grey", :size=>"l", :wt=>:heavy}]
Run Code Online (Sandbox Code Playgroud)
你可以试试:
ary = input.map {|k,v| [k].product v}
output = ary.shift.product(*ary).map {|a| Hash[a]}
Run Code Online (Sandbox Code Playgroud)
结果:
[
{:color=>"blue", :size=>"s"},
{:color=>"blue", :size=>"m"},
{:color=>"blue", :size=>"l"},
{:color=>"grey", :size=>"s"},
{:color=>"grey", :size=>"m"},
{:color=>"grey", :size=>"l"}
]
Run Code Online (Sandbox Code Playgroud)