ruby life questions
ruby life questions

Reputation: 129

Convert and modify ruby hash to new hash

How could I convert my hash to 2 very different hashes?

My hash:

{ "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. Desired hash: (all values from my hash)

[{ 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. Desired hash:

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

Please note: empty array in my hash shouldn't add any images to color variation, but should add variation with empty image string. (All shown in examples)

Upvotes: 1

Views: 62

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110645

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

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

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

Upvotes: 2

Related Questions