lol*_*lix -4 ruby ruby-on-rails
我怎样才能转化array1为hash1Ruby的?
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)
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)
| 归档时间: |
|
| 查看次数: |
533 次 |
| 最近记录: |