我主要关注" 4"根据案例next_choice声明。我想在库存哈希中挑出键值对,然后将其与sell_inventory哈希值进行比较,如果库存值大于sell_inventory中的值,则从库存值中减去两者的差值。完成所有这些后,我想清除sell_inventory哈希值,这样如果再次选择选项4,我可以重复这个过程。我无法弄清楚如何做到这一点,因为当涉及到红宝石哈希时,我会变成绿色。
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
答案 0 :(得分:1)
我不确定sell_inventory
哈希的用途。如果您只是希望用户输入一个项目,然后从库存中减去该项目,则可以执行此操作。
示例,说库存设置如下:
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]
库存现在包含数量为2的铅笔:
inventory = { 'pencil' => 2 }
在上面的示例中,有一个数量为3的铅笔。变量items_to_sell设置为铅笔(可能通过用户输入),并且amount_to_sell变量设置为1(也许可以通过用户输入)。然后,只有在有意义的情况下(已输入的编号小于或等于当前库存量),才会从库存中减去该金额。