ruby - Better way to map multiple values (inject) -
please suggest improve (ruby-ish) way summarise mutiple entries in 1 go given code below:
def summary_totals pay_paid, pay_unpaid = 0, 0 rec_paid, rec_unpaid = 0, 0 net_paid, net_unpaid = 0, 0 summary_entries.each |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
update: need rewrite each
loop (which sums 6 variables) in improve ruby style.
"better" subjective, guess want utilize inject summing. symbol argument inject can used create nice , concise. if pass result straight constructors, there's no need local variables, eg:
pay = paidunpaidentry.new( summary_entries.map { |e| e.payable.paid }.inject(:+), summary_entries.map { |e| e.payable.unpaid }.inject(:+) ) # etc
ruby collections
No comments:
Post a Comment