2017-02-17 84 views
0

我試圖將散列數組轉換爲散列值,並將其作爲散列元素之一作爲數組中的一個元素。在紅寶石中將散列數組轉換爲單個散列

例如:a = [{"active_accounts": 3, "id": 5}, {"active_accounts": 6, "id": 1}

我想這個數組轉換爲

a = {5: {"active_accounts": 3}, 1: {"active_accounts": 6}} 

我曾嘗試通過循環陣列上和訪問個人散列特定鍵做但似乎並不上班。任何線索將不勝感激。

+0

能否請您發佈自己嘗試過的代碼。 –

+0

'response = Hash.new a.each do | key | response [key [:id]] = {「active_accounts」:key [:active_accounts]} end response' –

回答

2
a.each_with_object({}) {|obj , hash| hash.merge!(Hash[obj[:id], Hash["active_accounts",obj[:active_accounts]]])} 

# {5=>{"active_accounts"=>3}, 1=>{"active_accounts"=>6}} 

希望它能幫助。

+0

它確實沒有Rangnath。 :) –

1

安全的變體,映射陣列(同"id"預期和妥善處理):

a.group_by { |e| e.delete("id") } 

正是你問:

a.group_by { |e| e.delete("id") } 
.map { |k, v| [k, v.first] } 
.to_h 
+0

非常感謝mudasobwa。偉大的幫助。 –

1

還有一個可能的解決方案)

a.map { |hash| [hash.delete(:id), hash] }.to_h 
#=> {5=>{:active_accounts=>3}, 1=>{:active_accounts=>6}}