ruby将嵌套数组转换为hash

oxf4rvwz  于 2023-10-17  发布在  Ruby
关注(0)|答案(6)|浏览(121)

有没有一种优雅的方法可以将形式为

[["a", 1], ["a", 2], [nil, 3], [nil, 4], ["b", 6], ["b", 8]]

转换成散列形式

{"a" => [1,2], nil => [3,4], "b" => [6,8]}
ercv8c1e

ercv8c1e1#

这是一种方法:

arr = [["a", 1], ["a", 2], [nil, 3], [nil, 4], ["b", 6], ["b", 8]]

h = Hash.new {|hash, key| hash[key] = []}
arr.each {|e| h[e[0]] << e[1]}
p h #=> {"a"=>[1, 2], nil=>[3, 4], "b"=>[6, 8]}
i2loujxw

i2loujxw2#

ary = [['a', 1], ['a', 2], [nil, 3], [nil, 4], ['b', 6], ['b', 8]]

ary.group_by(&:first).
# => { 'a' => [['a', 1], ['a', 2]], nil => [[nil, 3], [nil, 4]], 'b' => [['b', 6], ['b', 8]] }
  map {|k, v| [k, v.map(&:last)] }.
# => [['a', [1, 2]], [nil, [3, 4]], ['b', [6, 8]]]
  to_h
# => { 'a' => [1, 2], nil => [3, 4], 'b' => [6, 8] }
vojdkbi0

vojdkbi03#

一种方法可以是:

array = [['a', 1], ['a', 2], [nil, 3], [nil, 4], ['b', 6], ['b', 8]]
array.each_with_object(Hash.new{|h,k| h[k] = []}) {|a, obj| obj[a.first] << a.last }
# => {"a"=>[1, 2], nil=>[3, 4], "b"=>[6, 8]}
goucqfw6

goucqfw64#

array.each_with_object({}){|a, h| (h[a.first]||=[] )<< a.last }
jslywgbw

jslywgbw5#

为什么不试试这个神奇的方法:

  • n = [[“a”,1],[“a”,2],[nil,3],[nil,4],[“B”,6],[“B”,8]]*
    Hash[哈希]
70gysomp

70gysomp6#

ary = [['a', 1], ['a', 2], [nil, 3], [nil, 4], ['b', 6], ['b', 8]]
ary.group_by(&:first).map {|k, v| {k => v.map(&:last)} }

相关问题