2009-08-05 37 views
1

我有爲了討論看起來像這樣的數組:如何合併Ruby中數組中的子數組?

a = [[1,100], [2,200], [3,300], [2,300]] 

這四個子陣列,我想合併任何其中第一個元素是重複的。所以在上面的例子中,我想合併第2和第4個子數組。但是,需要注意的是,在匹配子陣列中的第二個元素不同的地方,我想保持較高的值。

所以,我希望看到這樣的結果:

a = [[1,100], [3,300], [2,300]] 

這個小難題是我上面的紅寶石技能,讓我轉向社區尋求幫助一點點。任何有關如何解決這個問題的指導都非常感謝。

感謝

回答

5
# Get a hash that maps the first entry of each subarray to the subarray 
# requires 1.8.7+ or active_support (or facets, I think) 
hash = a.group_by { |first, second| first } 
# Take each entry in the hash and select the biggest entry for each unique key 
hash.map {|k,v| v.max } 
+0

出色的作品。謝謝 :) – aaronrussell 2009-08-05 23:03:21