Created
May 8, 2015 02:20
-
-
Save erickuhn19/a2fe95052eb8716e14fe to your computer and use it in GitHub Desktop.
price_calculator
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_relative 'local_grocery' | |
class Cart | |
attr_accessor :name | |
attr_accessor :cart | |
attr_accessor :convert | |
def initialize(name) | |
@name = name | |
@all_items = Hash.new(0) | |
@cart = [] | |
@cart_with_quantities = Hash.new(0) | |
end | |
def add_items_to_hash(item) | |
@all_items[item.name] += item.price | |
end | |
def ask_user | |
puts "Please enter all the items purchased separated by a comma" | |
@cart = gets.chomp.split(',') | |
convert_cart_to_quantities | |
end | |
def convert_cart_to_quantities | |
@cart.each do |name| | |
@cart_with_quantities[name] += 1 | |
end | |
puts @cart_with_quantities | |
end | |
def calculate_cart | |
total = @cart_with_quantities.merge(@all_items) {|key, oldval, newval| newval * oldval } | |
how_much = total.values | |
final = how_much.inject(:+) | |
puts final.round(2) | |
end | |
end |
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 LocalGrocery | |
attr_accessor :name | |
attr_accessor :price | |
def initialize(name, price=0) | |
@name = name | |
@price = price | |
end | |
end |
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_relative 'local_grocery' | |
require_relative 'cart' | |
milk = LocalGrocery.new("milk", 3.97) | |
bread = LocalGrocery.new("bread", 2.17) | |
banana = LocalGrocery.new("banana", 0.99) | |
apple = LocalGrocery.new("apple", 0.89) | |
lets_go = Cart.new("Lets Go") | |
lets_go.add_items_to_hash(milk) | |
lets_go.add_items_to_hash(bread) | |
lets_go.add_items_to_hash(banana) | |
lets_go.add_items_to_hash(apple) | |
lets_go.ask_user | |
lets_go.calculate_cart |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment