Created
October 21, 2013 20:06
-
-
Save benjaminEwhite/7090056 to your computer and use it in GitHub Desktop.
Thinkful | Ruby on Rails | Tip Calculator Part 5
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
require "optparse" | |
def calculate_rate(base, percentage) | |
return base * percentage/100 | |
end | |
def calculate_meal_costs(meal_base, tax_rate, tip_rate) | |
tax_value = calculate_rate(meal_base, tax_rate) | |
meal_with_tax = tax_value + meal_base | |
tip_value = calculate_rate(meal_with_tax, tip_rate) | |
total = meal_with_tax + tip_value | |
meal_info = {:meal_base => meal_base, | |
:tax_rate => tax_rate, | |
:tax_value => tax_value, | |
:tip_rate => tip_rate, | |
:tip_value => tip_value, | |
:total => total} | |
return meal_info | |
end | |
options = {} | |
optparse = OptionParser.new do |opts| | |
opts.on("-m", "--meal MEAL", Float, | |
"raw meal cost as integer or float") do |meal| | |
options[:meal] = meal | |
end | |
opts.on("-x", "--tax TAX", Float, | |
"tax percent as integer or float") do |tax| | |
options[:tax] = tax | |
end | |
opts.on("-t", "--tip TIP", Float, | |
"tip percent as integer or float") do |tip| | |
options[:tip] = tip | |
end | |
end | |
begin | |
optparse.parse! | |
mandatory = [:meal, :tax, :tip] | |
missing = mandatory.select{ |param| options[param].nil? } | |
if not missing.empty? | |
puts "Missing inputs: #{missing.join(', ')}" | |
puts optparse | |
exit | |
end | |
rescue OptionParser::InvalidOption, OptionParser::MissingArgument | |
puts $!.to_s | |
puts optparse | |
exit | |
end | |
meal_info = calculate_meal_costs(options[:meal], options[:tax], options[:tip]) | |
print "The pre-tax cost of your meal was $%.2f.\n" % meal_info[:meal_base] | |
print "At %d%%, tax for this meal is $%.2f.\n" % [meal_info[:tax_rate], meal_info[:tax_value]] | |
print "For a %d%% tip, you should leave $%.2f.\n" % [meal_info[:tip_rate], meal_info[:tip_value]] | |
print "The grand total for this meal is then $%.2f.\n" % meal_info[:total] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment