Ruby Hashes
Store key-value pairs and iterate over them.
Ruby
scores = { "Ada" => 91, "Grace" => 88 }
scores["Linus"] = 79
scores.each do |name, score|
puts "#{name}: #{score}"
end
puts scores.sizeOutput
Ada: 91 Grace: 88 Linus: 79 3
Explanation
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.
Explore the dry run
Guided walkthroughReady
1
scores = { "Ada" => 91, "Grace" => 88 }2
scores["Linus"] = 793
scores.each do |name, score|4
puts "#{name}: #{score}"5
end6
puts 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 |
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.