有没有一种优雅的方法可以将形式为
[["a", 1], ["a", 2], [nil, 3], [nil, 4], ["b", 6], ["b", 8]]
转换成散列形式
{"a" => [1,2], nil => [3,4], "b" => [6,8]}
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]}
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] }
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]}
goucqfw64#
array.each_with_object({}){|a, h| (h[a.first]||=[] )<< a.last }
jslywgbw5#
为什么不试试这个神奇的方法:
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)} }
6条答案
按热度按时间ercv8c1e1#
这是一种方法:
i2loujxw2#
vojdkbi03#
一种方法可以是:
goucqfw64#
jslywgbw5#
为什么不试试这个神奇的方法:
Hash[哈希]
70gysomp6#