2016-10-13 117 views
0

我是紅寶石新手散列到哈希紅寶石

我有一個哈希值與鍵=>值對的大集合。我想根據關鍵將這個散列分成散列。

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

我希望以下結果:

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

感謝您的幫助!

回答

2

你可以做這樣的事情:

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]]}] 
0

通用的方法來完成,這將是:

hash.dup 
    .group_by(&:shift) 
    .map(&%i|label values|.method(:zip)) 
    .map(&:to_h)