从其他数组更新哈希值数组

时间:2015-10-11 14:29:45

标签: arrays ruby hash

我有一个哈希:

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

3 个答案:

答案 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)

< p>作为@ sawa的答案的变体,如果你不想改变< code> h< / code>,OP的示例哈希,你可以这样做:< / p为H. < pre>< code> a = [317,318,319,320,340,358,365] h.merge(h){| _,v | a.shift(v.size)}    #=> {" grey" => [317,318,319],"石南花蓝" => [320,340,358],    #" indigo" => [],"深灰色" => [365] < /代码>< /预> < p>这使用< a href =" http://docs.ruby-lang.org/en/2.0.0/Hash.html#method-i-merge"的rel =" nofollow的">哈希#合并< / A>使用块来确定两个哈希中存在的键的值,这里是所有键。< / p>

答案 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]}