Skip to content

Instantly share code, notes, and snippets.

@joshnesbitt
Created August 11, 2015 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshnesbitt/98e74f498a1d549de049 to your computer and use it in GitHub Desktop.
Save joshnesbitt/98e74f498a1d549de049 to your computer and use it in GitHub Desktop.
price_list = "orange = 10p apple = 20p bread = £1.10 tomato = 25p cereal = £2.34"
list = <<-LIST
list
orange
apple
apple
orange
tomato
cereal
bread
orange
tomato
LIST
class Catalog
PARSE_REGEX = /(\w+)\s=\s£?([\d.]+)p?/
def initialize(raw_prices)
@prices = parse(raw_prices)
end
def parse(raw)
matches = raw.scan(PARSE_REGEX)
matches.inject({}) do |buffer, match|
buffer.tap do |hash|
name = match[0]
price = coerce_price(match[1])
hash[name] = price
end
end
end
def lookup(name)
@prices[name]
end
private
def coerce_price(raw)
price = raw.include?('.') ? (raw.to_f * 100) : raw
price.to_i
end
end
class Basket
def initialize(raw_list)
@items = parse(raw_list)
end
def parse(raw)
raw.split.tap { |r| r.shift }
end
def each(&block)
@items.each(&block)
end
end
class Checkout
def initialize(prices, basket)
@prices, @basket = prices, basket
@total = 0
end
def process
@basket.each do |item|
@total += @prices.lookup(item)
end
end
def total
@total
end
end
catalog = Catalog.new(price_list)
basket = Basket.new(list)
checkout = Checkout.new(catalog, basket)
checkout.process
puts "The price of the shopping list is: £%.2f" % (checkout.total.to_f / 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment