Ruby collections: hashes
This course covers Ruby hashes, which store each value under a key instead of a position. It starts with the symbol shorthand and the hash rocket syntax, reading values with [] and the difference between symbol and string keys. It then covers adding, updating and removing entries, checking keys and values with key?, value? and fetch, and getting keys and values in insertion order. The last lessons cover merge and merge!, nested hashes with dig, and a small order summary challenge that combines these methods.
What you'll learn
- ✓Creating hashes with the symbol shorthand or the hash rocket syntax
- ✓Adding, updating and removing keys, and how hashes mutate in place
- ✓Choosing between [], fetch and key? for lookups
- ✓Reading keys and values in guaranteed insertion order
- ✓Combining hashes with merge, merge! and a conflict block
- ✓Reading nested hashes and arrays safely with dig
Creating and accessing hashes
Arrays store values by position, like fruits[0] for the first one. A hash stores each value under a name, a key, and looks it up by that name.
Read the full lesson free →Curriculum
7 lessonsCreating and accessing hashes
Hash literals with symbol shorthand or rockets, reading values with [], and why :name and "name" differ.
Adding, updating, and removing
Using hash[key] = value to add or update, delete to remove, and how both change the original hash.
Checking keys and values
Checking keys with key?, values with value?, and using fetch to raise KeyError or return a default.
keys, values, and order
Getting keys and values as arrays, relying on insertion order, and converting a hash to pairs with to_a.
Merging hashes
Combining hashes with merge or merge!, merging several at once, and resolving key collisions with a block.
Nested hashes and dig
Reading hashes inside hashes, why a missing middle key crashes chained [], and how dig returns nil instead.
Putting it together: a small challenge
An order summary method that combines [], values, keys, fetch with a default and dig, then a challenge.