数组Ruby Hash与循环

时间:2015-04-02 09:46:00

标签: ruby ruby-on-rails-4

我有这个哈希:

{: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'}

1 个答案:

答案 0 :(得分: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"}]