基本上我有一个像这样的哈希数组:
[
{ :id => 20, :total => 1, :total2 => 0 },
{ :id => 21, :total => 1, :total2 => 0 },
{ :id => 22, :total => 2, :total2 => 0 },
{ :id => 23, :total => 1, :total2 => 0 },
{ :id => 20, :total => 1, :total2 => 0 },
{ :id => 21, :total => 1, :total2 => 0 },
{ :id => 22, :total => 1, :total2 => 1 },
{ :id => 23, :total => 1, :total2 => 0 }
]
我希望数组像这样对最后两个哈希列求和,保持第一个 ( :id
) 作为标识符:
[
{ :id => 20, :total => 2, :total2 => 0 },
{ :id => 21, :total => 2, :total2 => 0 },
{ :id => 22, :total => 3, :total2 => 1 }
]
我环顾四周,似乎.inject()
在这种情况下使用了该方法,但我无法真正弄清楚语法/如何使用它。
我正在寻找的是将第一列(:id
)保留为 ID 字段;如果有另一个具有此 ID 的哈希,就像我上面的示例一样,则应将两个哈希相加。