2015-05-29 73 views

回答

2
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] } 
+0

注:'to_h'將僅用於Ruby的2.1或以上的工作。 – Surya

+0

thx對於所有的建議,我要用'Hash [array.group_by(&:first).map {| k,v | [k,v.map(&:last)]}]'因爲我認爲它是最可讀的(?) – margo

3

這是一個方式:

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]} 
1

單程可能是:

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]} 
0
ary = [['a', 1], ['a', 2], [nil, 3], [nil, 4], ['b', 6], ['b', 8]] 
ary.group_by(&:first).map {|k, v| {k => v.map(&:last)} } 
0
array.each_with_object({}){|a, h| (h[a.first]||=[])<< a.last }