2015-04-02 334 views
-6

陣列我有這個哈希:紅寶石哈希與環

{:id => [RN1223,BN3233], :name => ['Red Ring','Blue Bangles'], :category => ['Ring','Bangles']} 

而且我想獲得一個新的Hash以下格式:

{:id => 'RN1223', :name => 'Red Ring', :category => 'Ring'}, 
{:id => 'BN3233', :name => 'Blue Bangles', :category => 'Bangles'} 
+0

什麼是你的問題? – sawa 2015-04-02 10:16:07

+0

我有這個散列 {:id => [RN1223,BN3233],:name => ['Red Ring','Blue Bangles'],:category => ['Ring','Bangles']} 我想轉換成這種形式 {:ID => 'RN1223',:名稱=> '紅圈',:類=> '戒指'}, {:ID => 'BN3233',:名稱=>'藍色手鐲',:category =>'手鐲'} – 2015-04-02 10:19:43

回答

1
hsh = {:id => ['RN1223','BN3233'], 
     :name => ['Red Ring','Blue Bangles'], 
     :category => ['Ring','Bangles']} 
hsh.values.transpose.map {|arr| Hash[[:id, :name, :category].zip arr]} 
# => [{:id=>"RN1223", :name=>"Red Ring", :category=>"Ring"}, 
#  {:id=>"BN3233", :name=>"Blue Bangles", :category=>"Bangles"}]