2015-09-01 113 views
0

我有一個名爲disciplines低於這個哈希:如何將此散列轉換爲哈希數組?

disciplines = {"Architecture"=>"architecture", "Auditing"=>"auditing", "Consulting"=>"consulting", "Delivery"=>"delivery", "Development"=>"development", "Engineering"=>"engineering", "Environment/IT"=>"environment", "Graphic Design"=>"graphic_design", "Management"=>"management", "Requirements"=>"requirements", "Research"=>"research", "Support"=>"support", "System Design"=>"system_design", "Test & Eval"=>"test_and_evaluation", "Writing"=>"writing"} 

而且我希望把它轉換成散列的數組,看起來像這樣:

[{"name"=>"Architecture", "value"=>"architecture"}, {"name"=>"Auditing", "value"=>"auditing"}, {"name"=>"Consulting", "value"=>"consulting"}, {"name"=>"Delivery", "value"=>"delivery"}, {"name"=>"Development", "value"=>"development"}, {"name"=>"Engineering", "value"=>"engineering"}, {"name"=>"Environment/IT", "value"=>"environment"}, {"name"=>"Graphic Design", "value"=>"graphic_design"}, {"name"=>"Management", "value"=>"management"}, {"name"=>"Requirements", "value"=>"requirements"}, {"name"=>"Research", "value"=>"research"}, {"name"=>"Support", "value"=>"support"}, {"name"=>"System Design", "value"=>"system_design"}, {"name"=>"Test & Eval", "value"=>"test_and_evaluation"}, {"name"=>"Writing", "value"=>"writing"}] 

所以我只想把每一個鍵值對在第一哈希值,並將其映射到一個新的散列結果,其中現在的關鍵是name值現在值是value值,並把他們都在哈希

回答

7

你可以簡單地做數組:

disciplines.map{ |k, v| { 'name' => k, 'value' => v } } 

實現這一點。

這裏有一個演示:http://ideone.com/DBU3Ck

1

你也可以做到這樣:

array_of_hashes = disciplines.keys.inject([]) do |arr_of_hsh, item| 
     arr_of_hsh << ({name: item.downcase,value: item.capitalize}) 
    end 

輸出將是這個樣子:

# array_of_hashes => [{:name=>"architecture", :value=>"Architecture"}, {:name=>"auditing", :value=>"Auditing"}, {:name=>"consulting", :value=>"Consulting"}, {:name=>"delivery", :value=>"Delivery"}, {:name=>"development", :value=>"Development"}, {:name=>"engineering", :value=>"Engineering"}, {:name=>"environment/it", :value=>"Environment/it"}, {:name=>"graphic design", :value=>"Graphic design"}, {:name=>"management", :value=>"Management"}, {:name=>"requirements", :value=>"Requirements"}, {:name=>"research", :value=>"Research"}, {:name=>"support", :value=>"Support"}, {:name=>"system design", :value=>"System design"}, {:name=>"test & eval", :value=>"Test & eval"}, {:name=>"writing", :value=>"Writing"}]