如何分组哈希?

时间:2014-02-20 10:18:36

标签: ruby

我有一个哈希(见下文),我需要分组,但我不知道该怎么做。 我将这个数组用于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"}
    ]
  }

1 个答案:

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

输出

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

更新(如@mdesantis 所述,您的预期输出不正确,因此我确实将结构更改为有意义的内容。

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"}
              ]
    }
]