Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This accept values for 2 reports and then calculate weight average by sale revenue of gross profit and cogs of those reports.
# frozen_string_literal: true
Report = Struct.new(:sale_revenue, :gross_profit, :cogs)
def main
puts '## First report ##'
puts 'Input revenue: '
revenue1 = gets.chomp.to_f
puts 'Input gross profit: '
gp1 = gets.chomp.to_f
puts 'Input COGS: '
cogs1 = gets.chomp.to_f
puts '## Second report ##'
puts 'Input revenue: '
revenue2 = gets.chomp.to_f
puts 'Input gross profit: '
gp2 = gets.chomp.to_f
puts 'Input COGS: '
cogs2 = gets.chomp.to_f
# reports = [Report.new(100, 50, 5), Report.new(200, 100, 10)]
reports = [Report.new(revenue1, gp1, cogs1), Report.new(revenue2, gp2, cogs2)]
gp = weight_avg_gross_profit reports
cogs = weight_avg_cogs reports
puts "Weight avg gross profit = #{gp.round 2}" # 83.33 with the commented result
puts "Weight avg cogs = #{cogs.round 2}" # 8.33 with the commented result
end
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.to_f
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.