合并多个哈希数组并执行计算

时间:2014-02-03 20:21:57

标签: ruby arrays hash

我有2个哈希数组:

charges = [
   {:created=>"2014-01-28", :charge=>43677}, 
   {:created=>"2014-01-29", :charge=>37980}, 
   {:created=>"2014-01-30", :charge=>87354}, 
   {:created=>"2014-01-31", :charge=>43677}
]

fees = [
   {:created=>"2014-01-28", :fee=>3230}, 
   {:created=>"2014-01-29", :fee=>2380}, 
   {:created=>"2014-01-30", :fee=>2210}, 
   {:created=>"2014-01-31", :fee=>1870}
]

我需要做的是取fees并从每个日期charges中减去它们,然后输出计算出的数量:

totals = [
   {:created=>"2014-01-28", :amount=>40447}, 
   {:created=>"2014-01-29", :amount=>35600}, 
   {:created=>"2014-01-30", :amount=>85144}, 
   {:created=>"2014-01-31", :amount=>41870}
]

请注意,某一天可能不会同时收取费用和费用。所以在免费的情况下,你不会减去任何东西(或者你减去0)。如果是收费但没有收费,你会有一个负数。

2 个答案:

答案 0 :(得分:3)

我愿意

charges = [
   {:created=>"2014-01-28", :charge=>43677}, 
   {:created=>"2014-01-29", :charge=>37980}, 
   {:created=>"2014-01-30", :charge=>87354}, 
   {:created=>"2014-01-31", :charge=>43677}
]

fees = [
   {:created=>"2014-01-28", :fee=>3230}, 
   {:created=>"2014-01-29", :fee=>2380}, 
   {:created=>"2014-01-30", :fee=>2210}, 
   {:created=>"2014-01-31", :fee=>1870}
]

total = (fees + charges).group_by{ |h| h[:created] }.map do |k,v|
  val_hsh = v.each_with_object({}) do |h1,h2| 
    h1[:fee] ? h2[:fee] = h1[:fee] : h2[:charge] = h1[:charge]
  end
  {created: k, amount: val_hsh[:charge] - val_hsh[:fee]}
end

total 
# => [{:created=>"2014-01-28", :amount=>40447},
#     {:created=>"2014-01-29", :amount=>35600},
#     {:created=>"2014-01-30", :amount=>85144},
#     {:created=>"2014-01-31", :amount=>41807}]

<强>更新

charges = [
   {:created=>"2014-01-28", :charge=>43677}, 
   {:created=>"2014-01-29", :charge=>37980}, 
   {:created=>"2014-01-30", :charge=>87354}, 
   {:created=>"2014-01-31", :charge=>0}
]

fees = [
   {:created=>"2014-01-28", :fee=>3230}, 
   {:created=>"2014-01-29", :fee=>0}, 
   {:created=>"2014-01-30", :fee=>2210}, 
   {:created=>"2014-01-31", :fee=>1870}
]

total = (fees + charges).group_by{ |h| h[:created] }.map do |k,v|
  val_hsh = v.each_with_object({}) do |h1,h2| 
    h1[:fee] ? h2[:fee] = h1[:fee] : h2[:charge] = h1[:charge]
  end
  {created: k, amount: val_hsh[:charge] - val_hsh[:fee]}
end

total 
# => [{:created=>"2014-01-28", :amount=>40447},
#     {:created=>"2014-01-29", :amount=>37980},
#     {:created=>"2014-01-30", :amount=>85144},
#     {:created=>"2014-01-31", :amount=>-1870}]

答案 1 :(得分:0)

如果你想按照任何一个数组中存在的日期进行分组,你可以像@ArupRakshit上面那样进行分组:按日期分组然后计算。

否则,我建议你有一些id来识别条目,以防每天有多个条目 - 除非你故意通过设计将其删除。

假设数组按id:

排序,您可以使用以下内容
charges.zip(fees).collect { |charge, fee| { :created => charge[:created], :amount => charge[:charge] - fee[:fee] } }

=> [{:created=>"2014-01-28", :amount=>40447},
 {:created=>"2014-01-29", :amount=>35600},
 {:created=>"2014-01-30", :amount=>85144},
 {:created=>"2014-01-31", :amount=>41807}]