How do I update the key and value of a Ruby hash?

1

It turns out that I have a hash :

inventario = {"Notebooks"=> 4, "PC Escritorio"=> 6, "Routers"=> 10, "Impresoras"=> 6}

I need to update the information regarding any product, and that the inventory is updated.

I tried with map , hashmap and put , but apparently I'm not dealing with them well.

    
asked by Upset Grade 09.05.2018 в 15:25
source

1 answer

1

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}
    
answered by 09.05.2018 / 15:59
source