Ruby · Course navigation

Ruby Hashes

Store key-value pairs and iterate over them.

On this page
Before you start

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

Ruby
scores = { "Ada" => 91, "Grace" => 88 }
scores["Linus"] = 79
scores.each do |name, score|
  puts "#{name}: #{score}"
end
puts scores.size
Output
Ada: 91
Grace: 88
Linus: 79
3

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1scores = { "Ada" => 91, "Grace" => 88 }
2scores["Linus"] = 79
3scores.each do |name, score|
4 puts "#{name}: #{score}"
5end
6puts scores.size

Follow 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading