Created
July 13, 2017 05:09
-
-
Save vtno/667ec4e0c901e829251b01bbf4c97beb to your computer and use it in GitHub Desktop.
This accept values for 2 reports and then calculate weight average by sale revenue of gross profit and cogs of those reports.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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