gpt4 book ai didi

ruby-on-rails - Ruby 哈希组合

转载 作者:数据小太阳 更新时间:2023-10-29 07:09:47 27 4
gpt4 key购买 nike

对于一个电子商务应用程序,我试图将选项的散列(每个选项都有一系列选择)转换为代表这些选择组合的散列数组。例如:

# 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" } ]

Input 内部可能有额外的选项,每个选项的数量不确定,但它只会嵌套 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}]

关于ruby-on-rails - Ruby 哈希组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25653480/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com