在Ruby中将数组数组转换为哈希

时间:2016-01-12 17:12:32

标签: ruby-on-rails ruby

如何在Ruby中将array1转换为hash1

array1看起来像这样:

    [[80, "X", 12],
     [80, "X", 13],
     [80, "X", 14],
     [80, "X", 15],
     [80, "X", 16],
     [81, "Y", 20],
     [81, "Y", 21],
     [81, "Y", 22],
     [81, "Y", 23],
     [81, "Y", 24]]

hash1看起来像这样:

[['id' => 80, 'type' = >'X', numbers => {12,13,14,15,16}],
       ['id' => 81, 'type' = >'Y',numbers => {20,21,22,23,24}]]

3 个答案:

答案 0 :(得分:7)

array1
.group_by{|id, type, _| [id, type]}
.map{|(id, type), a| {"id" => id, "type" => type, "numbers" => a.map(&:last)}}
# => [
#      {"id"=>80, "type"=>"X", "numbers"=>[12, 13, 14, 15, 16]},
#      {"id"=>81, "type"=>"Y", "numbers"=>[20, 21, 22, 23, 24]}
#    ]

答案 1 :(得分:1)

每当使用Enumerable#group_by时(如@sawa),也可以使用Hash#update(aka merge!)的形式,它使用一个块来确定键的值。出现在两个哈希合并中:

arr = [[80, "X", 12],
       [80, "X", 13],
       [80, "X", 14],
       [80, "X", 15],
       [80, "X", 16],
       [81, "Y", 20],
       [81, "Y", 21],
       [81, "Y", 22],
       [81, "Y", 23],
       [81, "Y", 24]]

arr.each_with_object({}) { |(x,y,z),h|
  h.update(x=>{ "id"=>x, "type"=>y, "numbers"=>[z] }) { |_,o,n|
    { "id"=>o["id"], "type"=>o["type"], "numbers"=>o["numbers"]+n["numbers"] } } }.values
    #=> [{"id"=>80, "type"=>"X", "numbers"=>[12, 13, 14, 15, 16]},
    #    {"id"=>81, "type"=>"Y", "numbers"=>[20, 21, 22, 23, 24]}] 

答案 2 :(得分:-2)

您必须遍历您的array1并开始使用基本比较(if - else,group_by和mapping)将值分配到您想要的哈希值中,并保留以前ID的历史记录。

没有这样的红宝石方法可以做到这一点"神奇地"。