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

lol*_*lix -4 ruby ruby-on-rails

我怎样才能转化array1hash1Ruby的?

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]]
Run Code Online (Sandbox Code Playgroud)

hash1 看起来像这样:

[['id' => 80, 'type' = >'X', numbers => {12,13,14,15,16}],
       ['id' => 81, 'type' = >'Y',numbers => {20,21,22,23,24}]]
Run Code Online (Sandbox Code Playgroud)

saw*_*awa 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]}
#    ]
Run Code Online (Sandbox Code Playgroud)

  • 你是[fasstttt!](http://vignette2.wikia.nocookie.net/superheroes/images/2/24/Flash.jpg/revision/latest?cb=20140203094110) (2认同)