Episode 19a - Adding Values To A Hash

If you have a hash, it's easy to both retrieve and change any value. Let's define a hash to represent the amount of items in a store:

item_amounts = {"chair" => 5, "table" => 2}

To retrieve the value of how many tables there are in the store, you would use square brackets with the key name:

p item_amounts["table"]

The output of this code is:


If someone buys a table, now there's one less in the store. To redefine the value of the amount of tables, you would use square brackets with the key name and set it equal to the new value:

item_amounts["table"] = 1
p item_amounts

The output of this code is:

{"chair" => 5, "table" => 1}

Defining a brand new key and value to the hash looks very similar. Again, use square brackets with the key name (even though it doesn't exist yet!) and set it equal to the value you want.

item_amounts["desk"] = 7
p item_amounts

This will add a new key called "desk" to the hash with a value of 7. So the output of this code will be:

{"chair" => 5, "table" => 1, "desk" => 7}


  1. Start with the hash
    city_populations = {"Chicago" => 2700000}
    Add populations to the city_populations hash for New York City (8.4 million) and San Francisco (800,000). The result should be:
    {"Chicago" => 2700000, "New York City" => 8400000, "San Francisco" => 800000}
  2. Start with the array of arrays
    meals = [["breakfast", "pancakes with maple syrup"], ["lunch", "BLT"], ["dinner", "salmon with lemon rice"]]
    Each inner array’s first element describes the meal of the day (e.g. "breakfast"), and the second element in each inner array describes the particular meal (e.g. “pancakes with maple syrup”). Use the "each" method to create a hash called “meals_hash”. The keys should be the type of meal, and the values the specific type. The result should be:
    {"breakfast" => "pancakes with maple syrup", "lunch" => "BLT", "dinner" => "salmon with lemon rice"}
    Remember to use the each method, and don’t use the “to_h” method (that’s cheating!).