Reputation: 105
I am mainly looking at when "4" under the case next_choice statement. I want to single out the key-value pair in the inventory hash and then compare it to the sell_inventory hash, and if the value of inventory is greater than the value in sell_inventory then subtract the difference of the two from the inventory value. After I have done all of that I would like to clear the sell_inventory hash so that if option 4 is chose again, I can repeat the process. I cannot figure out how to do this as I'm pretty green when it comes to ruby hashes.
inventory = {}
sell_inventory = {}
p "Press enter to continue to program."
choice = gets.chomp.downcase
until choice.empty?
choice = gets.chomp.downcase
p "That is not a valid choice, please press enter to start."
end
while true
case choice
when ""
p "1. Show items in inventory"
p "2. Add new item to inventory"
p "3. Remove item from inventory"
p "4. Sell items"
p "5. Buy items"
next_choice = gets.chomp.downcase
case next_choice
when "1"
p "#{inventory}"
when "2"
p "What item would you like to store?"
item = gets.chomp
if inventory.has_key?(item)
p "You already have that item in storage."
else
inventory[item]
p "How many of the items would like to store?"
amount = gets.chomp.to_i
inventory[item] = amount
p "Items added to inventory."
end
when "3"
p "What item would you like to remove from inventory?"
item_to_remove = gets.chomp.to_i
if inventory.include?(item_to_remove)
inventory.delete_if {|item, id| item ==
item_to_remove}
else
p "That item is not in stock."
end
when "4"
p "What item would you like to sell?"
items_to_sell = gets.chomp
sell_inventory[items_to_sell]
p "How many of that item would you like to sell?"
amount_to_sell = gets.chomp.to_i
sell_inventory[items_to_sell] = amount_to_sell
end
when "exit"
break
end
end
Upvotes: 1
Views: 89
Reputation: 2021
I am unsure what the sell_inventory
hash is for. If you simply want the user to enter an item and then subtract that from inventory, you can do.
Example, say inventory is set as follows:
inventory = { 'pencil' => 3 }
items_to_sell = 'pencil' # user entered this
amount_to_sell = 1 # user entered this
inventory[items_to_sell] -= amount_to_sell if amount_to_sell <= inventory[items_to_sell]
inventory now contains a pencil with a quantity of 2:
inventory = { 'pencil' => 2 }
In the above example, there was a pencil with a quantity of 3. The variable items_to_sell was set to pencil (perhaps via user input) and the amount_to_sell variable was set to 1 (again perhaps via user input). Then that amount is subtracted from inventory only if it makes sense (the numbered entered was less than or equal to the amount currently in inventory).
Upvotes: 1