0

我在 Ruby 中有一个数组,如下所示:

@arr = [ [2.1, pass], 
         [2.1, fail],
         [2.1, pass],
         [2.1, unknown],
         [2.1, pass],
         [3.0, pass],
         [3.0, unknown],
         [3.1, pass],
         [3.1, fail] ]

我想对其应用某种散列或计算,以便我的输出应该是一个数组,如:

@result = [ [2.1, 3, 1, 1],
            [3.0, 1, 0, 1],
            [3.1, 1, 1, 0] ]

输出数组以这种格式显示结果 {version, no.of pass, no.of fail, no.of unknown}

4

2 回答 2

3

如果我稍微翻译一下你的表达...

@arr = [
  [2.1, :pass],
  [2.1, :fail],
  [2.1, :pass],
  [2.1, :unknown],
  [2.1, :pass],
  [3.0, :pass],
  [3.0, :unknown],
  [3.1, :pass],
  [3.1, :fail]]

那么问题就可以解决了...

@arr.group_by(&:first).values.map do |x|
  y = x.flatten
  [y[0], y.count(:pass), y.count(:fail), y.count(:unknown)]
end
于 2012-10-25T23:32:49.543 回答
0

这些不是有效的哈希。哈希必须有与之关联的键。这是初始示例中的数组哈希:

@arr = { something: [2.1, pass], 
         somethingelse: [2.1, fail],
         another: [2.1, pass],
         andanother: [2.1, unknown],
         whatever: [2.1, pass],
         whateverelse: [3.0, pass],
         key: [3.0, unknown],
         anotherkey: [3.1, pass],
         yetanother: [3.1, fail] }

哈希用 { 和 } 标记。数组是 [ 和 ]。如果你想要一个数组数组,你可以使用 [ 和 ]。

于 2012-10-25T23:19:51.087 回答