将哈希数组映射到Ruby中的键控哈希

时间:2015-07-13 07:31:18

标签: arrays ruby hash

我有一系列哈希,如下所示:

   array= [
      {
        "id"=> 101,
        "first_name"=> "xxx",
        "last_name"=> "G",
        "email"=> "xxx@yyyy.com",
        "phone_number"=> "555-555-5555"
      },
      {
        "id"=> 102,
        "first_name"=> "Jen",
        "last_name"=> "P",
        "email"=> "jen.p@example.com",
        "phone_number"=> "555-555-5555"
      }
    ]

我想将其转换为如下所示的哈希:

   array = {
          "101"=> 
          {
            "first_name"=> "xxx",
            "last_name"=> "G",
            "email"=> "xxx@yyyy.com",
            "phone_number"=> "555-555-5555"
          },
          "102"=>
          {
            "first_name"=> "Jen",
            "last_name"=> "P",
            "email"=> "jen.p@example.com",
            "phone_number"=> "555-555-5555"
          }
       }

我试过这个,但它不起作用:

    array.each do |a|
      a.map{|x| x[:id]}
    end

我如何在Ruby中执行此操作?我正在查看map函数,但在这种情况下不确定如何实现它。请帮忙!

3 个答案:

答案 0 :(得分:3)

这有效(破坏性):

>> Hash[array.map { |x| [x.delete("id"), x] }]
=>{
    101=>{
        "first_name"=>"xxx",
        "last_name"=>"G",
        "email"=>"xxx@yyyy.com",
        "phone_number"=>"555-555-5555"
    },
    102=>{
        "first_name"=>"Jen",
        "last_name"=>"P",
        "email"=>"jen.p@example.com",
        "phone_number"=>"555-555-5555"
    }
}

答案 1 :(得分:2)

试试这个:

array_h = Hash.new
array.each{|a| array_h[a["id"]] = a.reject{|e| e=='id' }}

#Output of array_h:
{
  101=>
    {
      "first_name"=>"xxx", 
      "last_name"=>"G", 
      "email"=>"xxx@yyyy.com", 
      "phone_number"=>"555-555-5555"
    }, 
  102=>
    {
      "first_name"=>"Jen", 
      "last_name"=>"P", 
      "email"=>"jen.p@example.com", 
      "phone_number"=>"555-555-5555"
    }
}

注意:这不会修改原始数组。

答案 2 :(得分:0)

删除array时的非破坏性变体(保留"id"):

{}.tap { |h| array.each { |a| nh = a.dup; h[nh.delete('id')] = nh } }
# => {101=>{"first_name"=>"xxx", "last_name"=>"G", "email"=>"xxx@yyyy.com", "phone_number"=>"555-555-5555"}, 102=>{"first_name"=>"Jen", "last_name"=>"P", "email"=>"jen.p@example.com", "phone_number"=>"555-555-5555"}} 
array
# => [{"id"=>101, "first_name"=>"xxx", "last_name"=>"G", "email"=>"xxx@yyyy.com", "phone_number"=>"555-555-5555"}, {"id"=>102, "first_name"=>"Jen", "last_name"=>"P", "email"=>"jen.p@example.com", "phone_number"=>"555-555-5555"}]