2013-03-22 193 views
0

我有一個2-d紅寶石陣列,它看起來是這樣的:紅寶石正則表達式 - 陣列

(Array) - @main.each do |value| 

value[0] value[1] value[2] 

3.0.1.2  TOTAL  Pass 
3.0.1.3  TOTAL  Pass 
3.4.0.1  8K   Fail 
3.5.4.3  9K   Fail 
3.5.0.9  TOTAL  Fail 

我想將它們單獨成2列,使得第一個應該有「合計」和所有行其他陣列應該有其他的一切。

回答

1

我不太明白你的陣列的字段,但你可以使用select和拒絕:

totals = @main.select{|entry| entry == "TOTAL"} 
others = @main.reject{|entry| entry == "TOTAL"} 

對於你的每個元素的任何測試。最初的@main將保持原樣,您可以使用總計和其他來訪問元素。

+1

與['可枚舉#partition'(HTTP做在[一通(http://stackoverflow.com/a/15583917/1074296)://紅寶石-doc.org/core-2.0/Enumerable.html#method--partition) – dbenhur 2013-03-23 06:06:53

1

你的問題沒有很好地解釋,但作爲一個快速猜測你想,我會建議看Array.group_by什麼,這是可枚舉的一部分:

ary = [ 
    %w[3.0.1.2  TOTAL  Pass], 
    %w[3.0.1.3  TOTAL  Pass], 
    %w[3.4.0.1  8K   Fail], 
    %w[3.5.4.3  9K   Fail], 
    %w[3.5.0.9  TOTAL  Fail], 
] 


ary.group_by{ |a| a.last } 

返回一個哈希,用鑰匙是最後一個元素的兩個不同值中的子陣列:

{ 
    "Pass" => [ 
     [0] [ 
      [0] "3.0.1.2", 
      [1] "TOTAL", 
      [2] "Pass" 
     ], 
     [1] [ 
      [0] "3.0.1.3", 
      [1] "TOTAL", 
      [2] "Pass" 
     ] 
    ], 
    "Fail" => [ 
     [0] [ 
      [0] "3.4.0.1", 
      [1] "8K", 
      [2] "Fail" 
     ], 
     [1] [ 
      [0] "3.5.4.3", 
      [1] "9K", 
      [2] "Fail" 
     ], 
     [2] [ 
      [0] "3.5.0.9", 
      [1] "TOTAL", 
      [2] "Fail" 
     ] 
    ] 
} 

訪問的一個或另一個是容易的:

ary.group_by{ |a| a.last }['Pass'] 
[ 
    [0] [ 
     [0] "3.0.1.2", 
     [1] "TOTAL", 
     [2] "Pass" 
    ], 
    [1] [ 
     [0] "3.0.1.3", 
     [1] "TOTAL", 
     [2] "Pass" 
    ] 
] 

或者:

ary.group_by{ |a| a.last }['Fail'] 
[ 
    [0] [ 
     [0] "3.4.0.1", 
     [1] "8K", 
     [2] "Fail" 
    ], 
    [1] [ 
     [0] "3.5.4.3", 
     [1] "9K", 
     [2] "Fail" 
    ], 
    [2] [ 
     [0] "3.5.0.9", 
     [1] "TOTAL", 
     [2] "Fail" 
    ] 
] 
4
@main = [ 
    %w[3.0.1.2  TOTAL  Pass], 
    %w[3.0.1.3  TOTAL  Pass], 
    %w[3.4.0.1  8K   Fail], 
    %w[3.5.4.3  9K   Fail], 
    %w[3.5.0.9  TOTAL  Fail], 
] 

totals, others = @main.partition{|a| a[1] == 'TOTAL'} 

# totals => [["3.0.1.2", "TOTAL", "Pass"], ["3.0.1.3", "TOTAL", "Pass"], ["3.5.0.9", "TOTAL", "Fail"]] 
# others => [["3.4.0.1", "8K", "Fail"], ["3.5.4.3", "9K", "Fail"]] 
+0

這會對它進行分區,但新陣列只有a [1]字段.....我希望其他字段保持不變太。 – 2013-03-23 09:10:22

+0

@sagarvikani當我運行它時,新數組包含原始元組。 ['Enumerable#partition'](http://ruby-doc.org/core-2.0/Enumerable.html#method-i-partition)基於塊的分區,但產生原始元素。 – dbenhur 2013-03-23 16:33:09

+0

@sagarvikani也許你可以更準確地向我們展示你的輸入,因爲你的問題有一個相當模糊的表示?我已經更新了這個答案,以說明我如何解釋你的'@ main'的結構。 – dbenhur 2013-03-23 16:40:00