0

私はこのような2Dルビー配列を持っています:

(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

最初の配列に「TOTAL」のすべての行があり、もう一方の配列に他のすべての行があるように、それらを2つの配列に分割したいと思います。

4

3 に答える 3

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"]]
于 2013-03-23T06:04:41.963 に答える
1

あなたの質問はうまく説明されていませんが、あなたが欲しいものの簡単な推測として、私はArray.group_byEnumerableの一部であるを見るのをお勧めします:

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 }

これはハッシュを返します。キーはサブ配列の最後の要素の2つの異なる値です。

{
    "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"
    ]
]
于 2013-03-23T00:19:21.450 に答える