2011-04-10 20 views
50

什麼是將此轉換如何扁平化數組的數組 - 但不是全部下來

[[["Club three Team one", 7800], ["Club three Team two", 7801]], [], [["Club four Team one", 7807], ["Club four Team two", 7808]], []] 

[["Club three Team one", 7800], ["Club three Team two", 7801], ["Club four Team one", 7807], ["Club four Team two", 7808]] 

在紅寶石的最佳方式呢?扁平化轉換這一切到

["Club three Team one", 7303, "Club three Team two", 7304, "Club four Team one", 7310, "Club four Team two", 7311] 

回答

93

使用flatten(1)http://apidock.com/ruby/Array/flatten

your_array = [[["Club three Team one", 7800], ["Club three Team two", 7801]], [], [["Club four Team one", 7807], ["Club four Team two", 7808]], []] 
your_array.flatten(1) 
#=> [["Club three Team one", 7800], ["Club three Team two", 7801], ["Club four Team one", 7807], ["Club four Team two", 7808]] 
+5

它可能是值得注意的,對老年人Ruby版本的方法:your_array.inject([]:CONCAT) – tokland 2011-04-10 15:24:45

+4

'扁平化(水平)'適用於1.8.7+紅寶石 – fl00r 2011-04-10 15:30:12

+0

@tokland對於大數組,它會慢得多 – fl00r 2012-09-26 07:44:09

相關問題