0

我有一个看起来像这样的二维 ruby​​ 数组:

(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 个数组,这样第一个数组的所有行都应该是“TOTAL”,而另一个数组应该有其他的。

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

我不太了解您的数组的字段是什么,但您可以使用选择和拒绝:

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

对于您对每个元素进行的任何测试。原始的@main 将保持原样,您可以使用总计和其他来访问元素。

于 2013-03-23T00:16:07.303 回答
1

您的问题没有得到很好的解释,但作为您想要的快速猜测,我建议您查看Array.group_by,这是 Enumerable 的一部分:

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"
    ]
]
于 2013-03-23T00:19:21.450 回答