映射多个值的更好方法(注入)

时间:2014-10-16 03:24:35

标签: ruby collections

请根据以下代码建议一种更好的(Ruby-ish)方式一次性汇总多个条目:

def summary_totals
  pay_paid, pay_unpaid = 0, 0
  rec_paid, rec_unpaid = 0, 0
  net_paid, net_unpaid = 0, 0

  summary_entries.each do |proj_summary|
    pay_paid   += proj_summary.payable.paid || 0
    pay_unpaid += proj_summary.payable.unpaid || 0
    rec_paid   += proj_summary.receivable.paid || 0
    rec_unpaid += proj_summary.receivable.unpaid || 0
    net_paid   += proj_summary.net.paid || 0
    net_unpaid += proj_summary.net.unpaid || 0
  end

  pay = PaidUnpaidEntry.new(pay_paid, pay_unpaid)
  rec = PaidUnpaidEntry.new(rec_paid, rec_unpaid)
  net = PaidUnpaidEntry.new(net_paid, net_unpaid)
  ProjectPaymentsSummary.new(pay, rec, net)
end

更新:您需要做的就是以更好的Ruby风格重写each循环(总结6个变量)。

1 个答案:

答案 0 :(得分:1)

"更好的"可能是主观的,但我想你想用注入来做总结。注入的符号参数可用于使其简洁明了。如果将结果直接传递给构造函数,则不需要局部变量,例如:

pay = PaidUnpaidEntry.new(
  summary_entries.map { |e| e.payable.paid   }.inject(:+),
  summary_entries.map { |e| e.payable.unpaid }.inject(:+)
)
# etc