Search code examples
rubyhashsubtraction

Ruby Hash: Subtracting quantities


I am trying to create a response that will allow the user to enter the key and value of the inventory to subtract from the inventory that already exists. So if there are 10 apples at the start of the inventory and I respond saying I'm selling 7 apples the remainder in the hash should be represented as 3 apples left.

I am a beginner and a bit lost so any explanation would be helpful. Thank you!

@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

Solution

  • @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
    

    At first I check whether product is an inventory product with Hash#key?. Otherwise I print an error. Then I subtract the quantity. Last I check the total quantity can't be negative.

    Hash.delete, which you tried, would remove the key-value-pair from the hash and returns the value. An example:

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