To update the value of a key in a hash, simply assign a new value directly using the method Hash # [] = ; for example:
inventario = { "Notebooks"=> 4, "PC Escritorio"=> 6, "Routers"=> 10, "Impresoras"=> 6 }
#=> {"Notebooks"=>4, "PC Escritorio"=>6, "Routers"=>10, "Impresoras"=>6}
To change the inventory from "Notebooks"
to 5
:
inventario["Notebooks"] = 5
#=> 5
inventario
#=> {"Notebooks"=>5, "PC Escritorio"=>6, "Routers"=>10, "Impresoras"=>6}
Since values are numbers, you can use +
or -
; For example, if you sell 2 "Impresoras"
(inventory decrease), you could do the following:
inventario["Impresoras"] -= 2
#=> 4
inventario
#=> {"Notebooks"=>5, "PC Escritorio"=>6, "Routers"=>10, "Impresoras"=>4}
Finally, you can substitute the values for variables, assuming they come from another section of code in your application; for example:
producto = "Routers"
items_vendidos = 3
inventario[producto] -= items_vendidos
#=> 7
inventario
#=> {"Notebooks"=>5, "PC Escritorio"=>6, "Routers"=>7, "Impresoras"=>4}