2017-02-17 86 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}}