Ruby“复杂”哈希操作

时间:2014-05-20 02:07:22

标签: ruby hash

在发送到数据库之前尝试合并一些数据。

给出以下哈希数组:

[
  {
    "id" => "A",
    "name" => "Batman",
    "entry" => "1"
  },
  {
    "id" => "A",
    "name" => "Batman",
    "entry" => "2"
  },
  {
    "id" => "B",
    "name" => "Superman",
    "entry" => "1"
  }
]

如何将其转换为:

[
  {
    "id" => "A",
    "name" => "Batman",
    "entries" => ["1","2"]
  },
  {
    "id" => "B",
    "name" => "Superman",
    "entries" => ["1"]
  }
]

谢谢

1 个答案:

答案 0 :(得分:1)

data = [
        {
          "id" => "A",
          "name" => "Batman",
          "entry" => "1"
        },
        {
          "id" => "A",
          "name" => "Batman",
          "entry" => "2"
        },
        {
          "id" => "B",
          "name" => "Superman",
          "entry" => "1"
        }
       ]

out = data.group_by{|h| [h['id'], h['name']]}.values.map do |hs|
  hs.first.merge({'entry' => hs.map{|h| h['entry']}})
end

p out
#=> [{"id"=>"A", "name"=>"Batman", "entry"=>["1", "2"]}, {"id"=>"B", "name"=>"Superman", "entry"=>["1"]}]