Jen Lijó Jen Lijó - 1 month ago 19
Ruby Question

split hash into hashes Ruby

I'm new to Ruby

I have a Hash with a big collection of key => value pairs. I would like to split this Hash into hashes depending on the key.

{..."LoopLabs "=>1, "Influanza "=>1, "Cleo Media "=>1, "Adento "=>1, "HireRadar "=>1, "FidorFactory "=>1, "Four Energy "=>1, "Liefery "=>5, "Weaveworks "=>1, "Gastrofix "=>1 }


I expect the following result:

{ label: "LoopLabs", values: [[1]] }
{ label: "Influanza", values: [[1]] }
{ label: "Liefery", values: [[5]] }
...


Thanks for the help!

Answer

You can do something like this:

hash = {"LoopLabs "=>1, "Influanza "=>1, "Cleo Media "=>1, "Adento "=>1, "HireRadar "=>1, "FidorFactory "=>1, "Four Energy "=>1, "Liefery "=>5, "Weaveworks "=>1, "Gastrofix "=>1 }
hash.map {|k,v| {label: k, values: [[v]]}}
# => [{:label=>"LoopLabs ", :values=>[[1]]},
# {:label=>"Influanza ", :values=>[[1]]},
# {:label=>"Cleo Media ", :values=>[[1]]},
# {:label=>"Adento ", :values=>[[1]]},
# {:label=>"HireRadar ", :values=>[[1]]},
# {:label=>"FidorFactory ", :values=>[[1]]},
# {:label=>"Four Energy ", :values=>[[1]]},
# {:label=>"Liefery ", :values=>[[5]]},
# {:label=>"Weaveworks ", :values=>[[1]]},
# {:label=>"Gastrofix ", :values=>[[1]]}]
Comments