Lesson 10 of 23 · Ruby 3.2
Look up values by key
Store named values in a hash and look them up with the matching key.
Learn
A Hash associates keys with values. A key identifies an entry without relying on its position. Write a hash between braces; in {name: "Ari"}, name: creates the Symbol key :name.
Use hash[key] to read a value and hash[key] = value to add or update an entry. A Symbol such as :name is a name value, distinct from the String "name". Use the same kind of key for writing and reading.
For the ordinary hashes in this lesson, an absent key returns nil. key?(key) checks whether an entry exists, including an entry whose stored value is nil.
Example
booking = {name: "Ari", seats: 2}
puts booking[:name]
booking[:seats] = 3
puts booking[:seats]Experiment
Predict the remaining stock. Change the sale from 2 items to 4 while keeping the lookup and update attached to the same key.
Predict both lookups. Change the second lookup to use a Symbol and compare the results.
Predict the checks. Add profile[:nickname] = "Ace" and see whether the presence check or only the value changes.