Created
January 31, 2015 13:29
-
-
Save revdan/fa6d16d667d1a4ca44ec to your computer and use it in GitHub Desktop.
Bill Splitter
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
class BillSplitter | |
attr_reader :total, :people, :tip | |
def initialize(options={}) | |
@total = options.fetch(:total).to_f | |
@people = options.fetch(:people, 2) | |
@tip = options.fetch(:tip, 10) | |
end | |
def calculate | |
"The cost is $%.2f per person " \ | |
"(including a $%.2f tip)" \ | |
% [price_per_person, tip_per_person] | |
end | |
private | |
def price_per_person | |
total / people + tip_per_person | |
end | |
def tip_per_person | |
calculated_tip / people | |
end | |
def calculated_tip | |
total / 100 * tip | |
end | |
end | |
#-~-~-~-~-~-# | |
# calculates the tip | |
p BillSplitter.new({ total: 104.80, people: 3, tip: 12 }).calculate | |
# => "The cost is $39.13 per person (including a $4.19 tip)" | |
# uses defaults of two people and a tip of 10% | |
p BillSplitter.new({ total: 104.80 }).calculate | |
# => "The cost is $57.64 per person (including a $5.24 tip)" | |
# if you don't provide a required key the error is helpful | |
p BillSplitter.new({ people: 3, tip: 8 }).calculate | |
# => `fetch': key not found: :total (KeyError) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment