将ruby哈希转换并修改为新哈希

时间:2015-10-11 16:01:10

标签: ruby hash

如何将我的哈希值转换为2个非常不同的哈希值?

我的哈希:

{ "grey"=> ["421_01.jpg", "421_02.jpg", "421_03.jpg"], 
  "heather blue"=> ["422_01.jpg", "422_02.jpg", "422_03.jpg"],
  "indigo"=> [], 
  "dark grey"=> ["435_01.jpg", "435_02.jpg", "435_03.jpg"] }

1。期望的哈希:(我的哈希值中的所有值)

[{ src: "421_01.jpg" },
 { src: "421_02.jpg" }, 
 { src: "421_03.jpg" }, 
 { src: "422_01.jpg" }, 
 { src: "422_02.jpg" }, 
 { src: "422_03.jpg" }, 
 { src: "435_01.jpg" }, 
 { src: "435_02.jpg" }, 
 { src: "435_03.jpg" }]

2。期望的哈希:

[{
   image: "421_01.jpg, 421_02.jpg, 421_03.jpg",
   attributes: [
     {
       name: "Color",
       option: "grey"
     }
   ]
 },
 {
   image: "422_01.jpg, 422_02.jpg, 422_03.jpg",
   attributes: [
     {
       name: "Color",
       option: "heather blue"
     }
   ]
 },
 {
   image: "",
   attributes: [
     {
       name: "Color",
       option: "indigo"
     }
   ]
 },
 {
   image: "435_01.jpg, 435_02.jpg, 435_03.jpg",
   attributes: [
     {
       name: "Color",
       option: "dark grey"
     }
   ]
 }]

请注意:我的哈希值中的空数组不应将任何图像添加到颜色变化中,但应添加带有空图像字符串的变体。 (全部显示在示例中)

1 个答案:

答案 0 :(得分:2)

h = { "grey"=> ["421_01.jpg", "421_02.jpg", "421_03.jpg"], 
      "heather blue"=> ["422_01.jpg", "422_02.jpg", "422_03.jpg"],
      "indigo"=> [], 
      "dark grey"=> ["435_01.jpg", "435_02.jpg", "435_03.jpg"] }

a = h.values
  #=> [["421_01.jpg", "421_02.jpg", "421_03.jpg"],
  #    ["422_01.jpg", "422_02.jpg", "422_03.jpg"],
  #    [],
  #    ["435_01.jpg", "435_02.jpg", "435_03.jpg"]] 

对于#1:

a.flat_map { |s| { src: s } }
  #=> [{:src=>"421_01.jpg"}, {:src=>"421_02.jpg"}, {:src=>"421_03.jpg"},
  #    {:src=>"422_01.jpg"}, {:src=>"422_02.jpg"}, {:src=>"422_03.jpg"},
  #    {:src=>"435_01.jpg"}, {:src=>"435_02.jpg"}, {:src=>"435_03.jpg"}] 

对于#2:

 h.map { |k,_| { image: a.shift.join(', '),
                 attributes: [{ name: "Color", option: k }] } }
  # => [{:image=>"421_01.jpg, 421_02.jpg, 421_03.jpg",
         :attributes=>[{:name=>"Color", :option=>"grey"}]},
        {:image=>"422_01.jpg, 422_02.jpg, 422_03.jpg",
         :attributes=>[{:name=>"Color", :option=>"heather blue"}]},
        {:image=>"", :attributes=>[{:name=>"Color", :option=>"indigo"}]},
        {:image=>"435_01.jpg, 435_02.jpg, 435_03.jpg",
         :attributes=>[{:name=>"Color", :option=>"dark grey"}]}]