Reducing complexity by refactoring with parameterization.
Update (13 July 2017): I fix the wrong weight average logic in the code and also provide a working example that you could run on your machine. :awesome:
Duplicate code is a major cause of unmaintainable scripts.
def weight_avg_gross_profit(reports)
# find total weight, sum of sale_revenue
total_weight = reports.reduce(0) { |sum, r| sum + r.sale_revenue }
# find sum products
sum_prod = reports.reduce do |sum, r|
sum + (r.percent_gross_profit * r.sale_revenue)
end
# simple weight average formula, (w1*x1 + w2*x2) / (w1 + w2)
sum_prod / total_weight
end
def weight_avg_gross_profit(reports)
# find total weight, sum of sale_revenue
total_weight = reports.reduce(0) { |sum, r| sum + r.sale_revenue }
# find sum products
sum_prod = reports.reduce(0) do |sum, r|
sum + (r.percent_gross_profit * r.sale_revenue)
end
# simple weight average formula, (w1*x1 + w2*x2) / (w1 + w2)
sum_prod / total_weight
end
def weight_avg_gross_profit(reports)
# find total weight, sum of sale_revenue
total_weight = reports.reduce(0) { |sum, r| sum + r.sale_revenue }
# find sum products
sum_prod = reports.reduce(0) do |sum, r|
sum + (r.cogs * r.sale_revenue)
end
# simple weight average formula, (w1*x1 + w2*x2) / (w1 + w2)
sum_prod / total_weight
end
Make it work, then make it right ❤
Notes: Ruby can dynamically calls a function by passing string or symbol to the method send
def weight_avg_gross_profit(reports)
weight_avg(reports, 'gross_profit')
end
def weight_avg_cogs(reports)
weight_avg(reports, 'cogs')
end
def weight_avg(reports, value)
total_weight = reports.reduce(0) { |sum, r| sum + r.sale_revenue }
sum_prod = reports.reduce(0) do |sum, res|
sum + (res.send(value) * res.sale_revenue)
end
sum_prod / total_weight
end
ruby parameterized_working_example.rb
Duplication is far cheaper than the wrong abstraction.
From us to your inbox weekly.