Reputation: 1693
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!
Upvotes: 0
Views: 828
Reputation: 121000
The generic way to accomplish this would be:
hash.dup
.group_by(&:shift)
.map(&%i|label values|.method(:zip))
.map(&:to_h)
Upvotes: 0
Reputation: 16506
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]]}]
Upvotes: 2