如何基于两个元素对子数组的元素进行分组

时间:2018-08-27 14:35:32

标签: arrays ruby sub-array

我的输入如下:

input = [
  ["account1",10,"Dr"],
  ["account1",20,"Dr"],
  ["account2",15,"Cr"],
  ["account1",25,"Cr"],
  ["account2",10,"Dr"],
  ["account1",10,"Cr"]
]

我正在尝试按帐户和交易类型(即DrCr)获得总和。我需要如下输出:

output = {
  ["account1","Dr"] => 30,
  ["account1","Cr"] => 35,
  ["account2","Dr"] => 10,
  ["account2","Cr"] => 15
}

我可以使用以下方式基于仅帐户来汇总金额:

input.each_with_object(Hash.new(0)) {|(f,g), h| h[f] += g}
# => {"account1"=>65, "account2"=>25}

3 个答案:

答案 0 :(得分:4)

您可以这样做:

input.each_with_object(Hash.new(0)) {|(f,g,i), h| h[[f,i]] += g}

=> {["account1", "Dr"]=>30, ["account2", "Cr"]=>15, ["account1", "Cr"]=>35, ["account2", "Dr"]=>10}

答案 1 :(得分:2)

input.group_by { |acc,_,title| [acc, title] }.
      transform_values { |v| v.sum { |a| a[1] } }
  #=> {["account1", "Dr"]=>30, ["account2", "Cr"]=>15, ["account1", "Cr"]=>35,
  #    ["account2", "Dr"]=>10}

第一步如下。

input.group_by { |acc,_,title| [acc, title] }
  #=> {
  #    ["account1", "Dr"]=>[["account1", 10, "Dr"], ["account1", 20, "Dr"]],
  #    ["account2", "Cr"]=>[["account2", 15, "Cr"]],
  #    ["account1", "Cr"]=>[["account1", 25, "Cr"], ["account1", 10, "Cr"]],
  #    ["account2", "Dr"]=>[["account2", 10, "Dr"]]
  #   }

答案 2 :(得分:1)

output = Hash.new(0)  # set a default value of zero, avoiding nil
input.each do |account, amount, transaction|
    output[[account, transaction]] += amount
end

output #  {["account1", "Dr"]=>30, ["account2", "Cr"]=>15, ["account1", "Cr"]=>35, ["account2", "Dr"]=>10}