我有一个哈希:
{
"grey" => ["anf_94748_01_prod1", "anf_94748_01_model1", "anf_94748_01_model2"],
"heather blue" => ["anf_106537_01_prod1", "anf_106537_01_model1", "anf_106537_01_model2"],
"indigo" => [],
"dark grey" => ["anf_94747_01_prod1"]
}
如何根据图像ID数组替换其值:
[317, 318, 319, 320, 340, 358, 365]
如果散列数组为空,则跳过它并转到下一个散列键,并为该映像分配id。期望的输出将是:
{
"grey" => [317, 318, 319],
"heather blue" => [320, 340, 358],
"indigo" => [],
"dark grey" => [365]
}
答案 0 :(得分:3)
h = {
"grey" => ["anf_94748_01_prod1", "anf_94748_01_model1", "anf_94748_01_model2"],
"heather blue" => ["anf_106537_01_prod1", "anf_106537_01_model1", "anf_106537_01_model2"],
"indigo" => [],
"dark grey" => ["anf_94747_01_prod1"]
}
a = [317, 318, 319, 320, 340, 358, 365]
h.each_value{|v| v.map!{a.shift}}
# =>
# {
# "grey"=>[317, 318, 319],
# "heather blue"=>[320, 340, 358],
# "indigo"=>[],
# "dark grey"=>[365]
# }
答案 1 :(得分:1)
答案 2 :(得分:0)
reduce
是一个很好的功能,可以在累积某些结果的同时通过数据结构。
imgs = [317, 318, 319, 320, 340, 358, 365]
input = {"grey"=>["anf_94748_01_prod1", "anf_94748_01_model1", "anf_94748_01_model2"], "heather blue"=>["anf_106537_01_prod1", "anf_106537_01_model1", "anf_106537_01_model2"], "indigo"=>[], "dark grey"=>["anf_94747_01_prod1"]}
input.reduce({}) { |acc, (k, xs)| acc[k] = imgs.shift(xs.count); acc}
# => {"grey"=>[317, 318, 319], "heather blue"=>[320, 340, 358], "indigo"=>[], "dark grey"=>[365]}