Ruby Hash:减去数量

时间:2017-01-19 14:36:13

标签: ruby hash subtraction

我正在尝试创建一个响应,允许用户输入库存的键和值,以从已存在的库存中减去。因此,如果在库存开始时有10个苹果,我回答说我卖的是7个苹果,剩下的哈希应该表示为剩下的3个苹果。

我是初学者,有点迷失,所以任何解释都会有所帮助。谢谢!

@inventory = {"apples" => 10, "bananas" => 10, "crackers" => 10, "breads" => 10}

def sell_inventory   
   puts "What food are we selling today?"       
   product = gets.chomp.downcase         
   puts "How many #{product} are we selling today?"        
   quantity = gets.to_i        
   @inventory.delete(product, quantity)         
end

1 个答案:

答案 0 :(得分:4)

@inventory = { "apples" => 10, "bananas" => 10, "crackers" => 10, "breads" => 10 }

def sell_inventory 
   puts "What food are we selling today?" 
   product = gets.chomp.downcase 

   puts "How many #{product} are we selling today?" 
   quantity = gets.to_i 

   if @inventory.key?(product)
     @inventory[product] -= quantity
     @inventory[product] = 0 if @inventory[product] < 0
   else
     puts "No inventory product: #{product}"
   end
end

首先,我检查product是否为Hash#key?的库存产品。否则我会打印错误。 然后我减去数量。最后我检查总量不能为负数。

您尝试过的

Hash.delete会从哈希中删除键值对并返回值。一个例子:

@inventory.delete("apples")
# => 8
@inventory
# => {"bananas"=>10, "crackers"=>10, "breads"=>10}