Ruby Hashes
Store key-value pairs and iterate over them.
On this page
Ruby arrays and blocks.
- Store key-value pairs and iterate over them.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
A hash maps keys to values. The literal { "Ada" => 91 } uses => between each key and value, and scores["Linus"] = 79 adds a new pair. Ruby hashes remember the order in which keys were added.
each with two block parameters yields the key and value of every pair. size returns the number of pairs.
Code example
scores = { "Ada" => 91, "Grace" => 88 }
scores["Linus"] = 79
scores.each do |name, score|
puts "#{name}: #{score}"
end
puts scores.sizeAda: 91 Grace: 88 Linus: 79 3
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
scores = { "Ada" => 91, "Grace" => 88 }scores["Linus"] = 79scores.each do |name, score| puts "#{name}: #{score}"endputs scores.sizeFollow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Create a hash with two pairs. | scores = {"Ada"=>91, "Grace"=>88} | — | |
| Add a third key. | scores has 3 pairs | — | |
| The block runs once per pair, in insertion order. | scores has 3 pairs | Ada: 91 Grace: 88 Linus: 79 | |
| Print the number of pairs. | scores has 3 pairs | Ada: 91 Grace: 88 Linus: 79 3 |
Behind the scenes
How Ruby processes this code
Ruby parses and executes the script. Blocks run when their methods invoke them.
Cost and common mistakes
Lookup and insert are O(1) on average; iteration is O(n).
- Looking up a missing key returns nil, not an error. Use fetch if you want a failure.
- Strings and symbols are different keys: "a" and :a are not the same.
Try it yourself
What does scores["Zed"] return?
Reveal answer and reasoning
nil, because that key is absent.