Hashes
Prerequisites: Arrays
A hash stores key-value pairs: you look up a value by its key instead of by its position. Other languages call this a dictionary or map.
Real-world analogy: a hash is like a contacts list. You don't find a phone number by its position in the list — you look it up by the person's name.
Syntax
user = { name: "Ada", age: 36, city: "London" }
name: is shorthand for a symbol key (:name). This is the
standard style. Keys can also be strings, written with => ("hash
rocket"):
prices = { "apple" => 0.5, "banana" => 0.25 }
Reading and changing values
user = { name: "Ada", age: 36 }
p user[:name]
p user[:email]
p user.fetch(:email, "no email")
user[:email] = "ada@example.com"
user[:age] += 1
user.delete(:name)
p user
p user.key?(:age)
p user.keys
p user.values
p user.size
"Ada"
nil
"no email"
{age: 37, email: "ada@example.com"}
true
[:age, :email]
[37, "ada@example.com"]
2
- A missing key returns
nilwith[]. fetchlets you give a default — or, with no default, raises aKeyErrorso a missing key can't slip through unnoticed.
Iterating
stock = { apples: 10, pears: 0, plums: 4 }
stock.each do |fruit, count|
puts "#{fruit}: #{count}"
end
apples: 10
pears: 0
plums: 4
Hashes keep the order in which keys were added.
Common mistakes
- Mixing string and symbol keys: a hash built with
name:won't finduser["name"]. Pick one style per hash. - Reading a missing key with
[]and getting a silentnil. Usefetchwhen the key must be there.
Practice
Create a hash of three countries and their capitals, add a fourth, then
print each pair as France → Paris.
Show solution
capitals = { "France" => "Paris", "Japan" => "Tokyo", "Peru" => "Lima" }
capitals["Kenya"] = "Nairobi"
capitals.each do |country, capital|
puts "#{country} → #{capital}"
end