2014-02-20 98 views
0

我得到了一個哈希(見下文),我需要組,但我不知道如何去做。 我將在iOS中使用此數組作爲表格部分(Rubymotion)。如何對散列進行分組?

散列看起來是這樣的,我想按職業:

[{"firstname" => "John", "lastname" => "Wayne", "profession" => "actor"},{"firstname" => "Oliva", "lastname" => "Newton", "profession" => "actor"},{"firstname" => "Terry", "lastname" => "Gilliam", "profession" => "director"}] 

我需要它看起來像這樣:

["actor" => [{"firstname" => "John", "lastname" => "Wayne", "profession" => "actor"},{"firstname" => "Oliva", "lastname" => "Newton", "profession" => "actor"}], "director" =>[{"firstname" => "Terry", "lastname" => "Gilliam", "profession" => "director"}] 

更新

這將是非常好,如果我能得到這個結構:

{ 
    "profession" => "actor", 
    "people" => 
    [ 
     {"firstname"=>"John", "lastname"=>"Wayne", "profession"=>"actor"}, 
     {"firstname" => "Oliva", "lastname" => "Newton", "profession" => "actor"} 
    ], 
"profession" => "director", 
    "people" => 
    [ 
     {"firstname" => "Terry", "lastname" => "Gilliam", "profession" => "director"} 
    ] 
    } 
+2

您輸入有錯構 –

+0

你更新的結構更是雪上加霜。 – sawa

+0

你不能有這樣的結構,''people''鍵不能在同一個散列表中出現一次以上 – mdesantis

回答

3

請執行以下使用Enumerable#group_by

a = [ 
     {"firstname" => "John", "lastname" => "Wayne", "profession" => "actor"}, 
     {"firstname" => "Oliva", "lastname" => "Newton", "profession" => "actor"}, 
     {"firstname" => "Terry", "lastname" => "Gilliam", "profession" => "director"} 
    ] 

a.group_by { |h| h["profession"] } 

輸出:(如@mdesantis提到

{ "actor"=> [ 
      {"firstname"=>"John", "lastname"=>"Wayne", "profession"=>"actor"}, 
      {"firstname"=>"Oliva", "lastname"=>"Newton", "profession"=>"actor"} 
      ], 
    "director"=> [ 
      {"firstname"=>"Terry", "lastname"=>"Gilliam", "profession"=>"director"} 
       ] 
} 

更新,你的預期輸出是不正確的,所以我沒有改變結構到有意義的東西。

a = [ 
     {"firstname" => "John", "lastname" => "Wayne", "profession" => "actor"}, 
     {"firstname" => "Oliva", "lastname" => "Newton", "profession" => "actor"}, 
     {"firstname" => "Terry", "lastname" => "Gilliam", "profession" => "director"} 
    ] 

result_hash = a.group_by { |h| h["profession"] }.map do |key,val| 
    {"profession" => key, "people" => val} 
end 

p result_hash 

輸出

[ 
    {"profession"=>"actor", 
    "people"=> [ {"firstname"=>"John", "lastname"=>"Wayne", "profession"=>"actor"}, 
       {"firstname"=>"Oliva", "lastname"=>"Newton", "profession" =>"actor"} 
       ] 
    }, 
    {"profession"=>"director", 
    "people"=>[ {"firstname"=>"Terry", "lastname"=>"Gilliam", "profession"=>"director"} 
       ] 
    } 
] 
+0

謝謝!我已經更新了一下我的問題。請看一看。 –

+0

@JonathanClark請檢查。 –

+0

@ArupRakshit他決定無視你。 – sawa

相關問題