Created
October 14, 2018 16:33
-
-
Save sevperez/4ec1ba790d05855da6d49c9c43693d19 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 AuctionHouse | |
| attr_accessor :items, :total_sales | |
| def initialize(items) | |
| @items = items | |
| @total_sales = 0 | |
| end | |
| def run_auction(bid_list) | |
| handle_bid_list(bid_list) | |
| finalize_sales | |
| end | |
| def announce_status | |
| announce_items | |
| announce_sales | |
| end | |
| private | |
| def handle_bid_list(bid_list) | |
| bid_list.each { |item, amount| handle_bid(item, amount) } | |
| end | |
| def handle_bid(item, amount) | |
| if item_exists?(item) && accept_bid?(item, amount) | |
| @items[item] = amount | |
| end | |
| end | |
| def item_exists?(item) | |
| @items.has_key?(item) | |
| end | |
| def accept_bid?(item, amount) | |
| @items[item].nil? || amount > @items[item] | |
| end | |
| def finalize_sales | |
| calculate_total_sales | |
| remove_sold_items | |
| end | |
| def calculate_total_sales | |
| @items.each_pair do |item, amount| | |
| @total_sales += amount unless amount.nil? | |
| end | |
| end | |
| def remove_sold_items | |
| @items = @items.select { |item, amount| @items[item].nil? } | |
| end | |
| def announce_items | |
| puts "Available items: " | |
| @items.keys.each_with_index { |item, idx| puts "#{idx + 1}: #{item}" } | |
| end | |
| def announce_sales | |
| puts "Total sales: #{dollarize_sales}" | |
| end | |
| def dollarize_sales | |
| "$" + @total_sales.to_s.reverse.scan(/.{1,3}/).join(",").reverse | |
| end | |
| end | |
| paintings = { "Night Watch" => nil, "American Gothic" => nil, "Tower of Babel" => nil, | |
| "Friend In Need" => nil, "Potato Eaters" => nil, "Red Balloon" => nil } | |
| auction_house = AuctionHouse.new(paintings) | |
| bids = [["Night Watch", 550000], ["Night Watch", 700000], ["American Gothic", 145000], | |
| ["Friend In Need", 180000], ["Potato Eaters", 240000], ["Potato Eaters", 300000], | |
| ["Red Balloon", 1500000], ["Red Balloon", 25], ["Red Balloon", 1800000]] | |
| auction_house.announce_status | |
| # Available items: | |
| # 1: Night Watch | |
| # 2: American Gothic | |
| # 3: Tower of Babel | |
| # 4: Friend In Need | |
| # 5: Potato Eaters | |
| # 6: Red Balloon | |
| # Total sales: $0 | |
| auction_house.run_auction(bids) | |
| auction_house.announce_status | |
| # Available items: | |
| # 1: Tower of Babel | |
| # Total sales: $3,125,000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment