通过相同的键Ruby将两个哈希与数组合并

时间:2016-06-27 09:10:33

标签: arrays ruby hash

我需要一些Ruby的帮助。我有两个从JSON解析的哈希。我使用此代码来解析文件:

document = JSON.load File.new("hosts.txt")
file = JSON.load File.new("admins.txt")

结果是两个大的哈希:

document={"total"=>13, "subtotal"=>13, "page"=>1, "per_page"=>20,
          "search"=>nil, "sort"=>{"by"=>nil, "order"=>nil},
          "results"=>[
             {"ip"=>"10", "environment_id"=>7, 
                 "medium_id"=>nil, "name"=>"one", "id"=>1},
             {"ip"=>"15", "environment_id"=>7, 
                 "medium_id"=>nil, "name"=>"two", "id"=>1},
             {"ip"=>"10.5", "environment_id"=>6, 
                 "medium_id"=>nil, "name"=>"four", "id"=>1}]}

file={"admins"=>[
           {"name"=>"one", "surname"=>"Mark", "email"=>"mark@o.com"},
           {"name"=>"two", "surname"=>"Adam", "email"=>"Adam@o.com"},
           {"name"=>"four", "surname"=>"Ami", "email"=>"Ami@o.com"}]}

从第一个哈希我只需要结果键中的信息,所以我已经完成了

data = document["results"]

我为第二个哈希做了同样的事情:

people = file["admins"]

现在,当“name”值相同时,我想将姓氏和电子邮件从人员数组移到数据数组,并有另外一个这样的哈希:

new = {"all_data"=>[
        {"ip"=>"10", "environment_id"=>7, "medium_id"=>nil,
           "name"=>"one", "id"=>1, "surname"=>"Mark", "email"=>"mark@o.com"},
        {"ip"=>"15", "environment_id"=>7, "medium_id"=>nil,
           "name"=>"two", "id"=>1, "surname"=>"Adam", "email"=>"Adam@o.com"},
        {"ip"=>"10.5", "environment_id"=>6, "medium_id"=>nil,
           "name"=>"four", "id"=>1, "surname"=>"Ami", "email"=>"Ami@o.com"}]}

你能帮助我解释它是如何运作的吗?

1 个答案:

答案 0 :(得分:1)

personal_data = file['admins'].map(&:dup)
                              .group_by { |e| e.delete('name') }

上面的dup / delete技巧不是必需的,因为在任何情况下都会正确处理下面的merge,但是为了语义清晰起见,这里就是这样。

document['results'].map do |h|
  h.merge(personal_data[h['name']].first) if personal_data[h['name']]
end

#⇒ [
#    {"ip"=>"10", "environment_id"=>7, "medium_id"=>nil, "name"=>"one",
#       "id"=>1, "surname"=>"Mark", "email"=>"mark@o.com"},
#    {"ip"=>"15", "environment_id"=>7, "medium_id"=>nil, "name"=>"two",
#       "id"=>1, "surname"=>"Adam", "email"=>"Adam@o.com"},
#    {"ip"=>"10.5", "environment_id"=>6, "medium_id"=>nil, "name"=>"four",
#       "id"=>1, "surname"=>"Ami", "email"=>"Ami@o.com"}]