Thuta Learning
Ruby
BasicProgrammingBeginner

Hashes

RubyLesson 1035 min

What you'll walk away with

  • Create hashes with symbol keys and add, update, read and delete entries
  • Choose between [], fetch and dig, knowing which returns nil and which raises KeyError
  • Count with Hash.new(0) and explain why Hash.new([]) shares one array between all keys
  • Transform hashes with each, select, map and transform_values, and rely on insertion order

Explain it simply

Explain it simply

A hash is a dictionary: instead of finding things by position, you find them by a label called a key. Look up :name in a user hash and you get "Aung"; look up :city and you get "Tokyo". Each entry is a key paired with a value, and the whole thing sits between curly braces.

Hashes are how Ruby describes anything with named parts: a user profile, a product, a settings file or the JSON that comes back from a web API. Because you ask for data by name, the code reads like the data it handles: user[:city] instead of user[2].

Problem → Why → Solution

The problem: the key is there, but you get nil

You have a user hash built with symbol keys, and you read it with a string: user["name"]. Ruby does not complain about the lookup. It simply returns nil, because the key :name and the key "name" are two different things, and the crash comes one step later when you call a method on the nil.

A second pain is counting. To count how often each word appears you need a place to keep a number per word, and you cannot add 1 to a key that does not exist yet. Without a default value you end up wrapping every increment in an if/else.

user_lookup.rb
user = { name: "Aung", city: "Tokyo" }
puts user["name"].upcase     # NoMethodError: undefined method 'upcase' for nil

Why does Ruby not complain about a missing key?

Hash lookups do not complain about a missing key by default: [] answers nil, and nil only fails later. The key's type is part of its identity, so :name, "name" and 1 are three different keys. Once you know that, you can choose a reading style that fails loudly where a key really must exist, and a default value that removes the if/else where a missing key has an obvious meaning.

Core concept: every key is paired with a value

A hash is written with curly braces and key: value pairs. The name: "Aung" form is shorthand for :name => "Aung", so the key is a symbol, a small immutable label that Ruby compares very quickly. You can also use strings or numbers as keys, but symbol keys are the convention for fixed field names, and the two kinds are not interchangeable: user[:name] finds the entry, user["name"] does not.

Reading, writing and deleting use the same brackets: user[:city] reads, user[:city] = "Osaka" adds or replaces, and user.delete(:city) removes. A hash remembers the order in which keys were first inserted, and each, map and keys follow that order. Updating an existing key keeps its place, while deleting a key and adding it again moves it to the end.

Reading a missing key is where hashes differ most from arrays, so the table lists the choices. Pick the one whose failure behavior matches your intent.

Read styleMissing key givesUse it when
h[:key]nila missing key is normal
h.fetch(:key)KeyError (key not found: :key)the key must exist
h.fetch(:key, default)the default you gavea fallback is fine
h.dig(:a, :b)nil if any level is missingreading nested data

A default value changes what [] returns for a missing key. Hash.new(0) is the classic counter: counts[word] += 1 works even for a word never seen, because the missing read gives 0. Be careful with a mutable default: Hash.new([]) hands out the very same array for every missing key, and since reading stores nothing, the hash itself stays empty. For lists, use the block form Hash.new { |hash, key| hash[key] = [] }, which creates and stores a new array per key.

Finally, Ruby 3.4 and later print symbol-key hashes as {name: "Aung", "k" => 1}, with a space around => for other keys, and the examples here come from Ruby 4.0.9. Older versions print the same hash as {:name=>"Aung", "k"=>1}. The data is identical; only the printed form changed.

Mental model: a labelled cabinet
  1. Pick a key, such as :name
  2. Ruby finds the entry for that key
  3. Missing key: nil, default or KeyError
  4. Entries keep their insertion order

A hash is a cabinet with a label on every drawer: the label is the key, what is inside is the value, and you have to type the label exactly.

General pattern

ruby
hash = { key: value, "text key" => value }   # symbol key shorthand, any key type
hash[:key]                    # value, or nil when the key is missing
hash[:key] = new_value        # add or replace an entry
hash.fetch(:key)              # value, or KeyError when the key is missing
hash.dig(:outer, :inner)      # nested read; nil if any level is missing
counts = Hash.new(0)          # missing keys read as 0 (and are not stored)
hash.transform_values { |value| new_value }

key: value is the shorthand for symbol keys, and other key types work with "text key" => value. [] gives nil, fetch raises KeyError when the key is absent, dig reads nested data safely level by level, and Hash.new(0) gives a counter.

Example: a user profile hash

This program builds a user profile with three symbol keys, reads one, adds another entry and loops over all the entries. The last two lines show the result for a missing key and print the whole hash in inspect form.

user.rb
user = {
  name: "Aung",
  role: "developer",
  city: "Tokyo"
}

puts user[:name]
user[:language] = "Ruby"

user.each do |key, value|
  puts "#{key}: #{value}"
end

p user[:email]
p user

Code breakdown

  1. Literalname: "Aung",

    name: "Aung" pairs the symbol key :name with the value "Aung". Entries are separated by commas, and one line per entry keeps even a long hash readable.

  2. Readputs user[:name]

    You read with the symbol inside brackets, which prints Aung. Writing user["name"] instead would give nil because the key is different.

  3. Adduser[:language] = "Ruby"

    Assigning to a key that does not exist yet adds a new entry at the end; assigning to an existing key replaces its value without moving it.

  4. Iterateuser.each do |key, value|

    each hands the block both the key and the value for every entry, in insertion order, which is why language appears last.

  5. Missing keyp user[:email]

    There is no :email, so Ruby returns nil instead of raising. If that nil is used without a check, a NoMethodError can follow one step later.

  6. Inspectp user

    p shows the hash in inspect form. Ruby 3.4 and later print {name: "Aung", ...}, while older versions print {:name=>"Aung", ...}. This output comes from Ruby 4.0.9.

You should see
Aung
name: Aung
role: developer
city: Tokyo
language: Ruby
nil
{name: "Aung", role: "developer", city: "Tokyo", language: "Ruby"}

Counting with defaults, and the shared-default trap

Counting words with Hash.new(0) needs no if/else at all. The rest of the code shows what goes wrong with Hash.new([]) and how the block form fixes it. Keep in mind that reading stores nothing, which is why shared prints as an empty {}.

defaults.rb
words = %w[tea milk tea sugar tea milk]
counts = Hash.new(0)
words.each { |word| counts[word] += 1 }
p counts
p counts["honey"]
p counts.key?("honey")

shared = Hash.new([])
shared[:a] << 1
shared[:b] << 2
p shared
p shared[:c]

grouped = Hash.new { |hash, key| hash[key] = [] }
grouped[:a] << 1
grouped[:b] << 2
p grouped

The output is {"tea" => 3, "milk" => 2, "sugar" => 1}, 0, false, {}, [1, 2] and {a: [1], b: [2]}. counts["honey"] gives 0, but "honey" is never stored, so key? says false. With shared, << changes the default array itself, so both :a and :b push 1 and 2 into that one array while the hash stays empty.

Safe reads: fetch and dig

Chaining brackets on nested hashes, as in config[:db][:host], breaks when a middle level is missing. dig solves that, while fetch gives a clear error for a key that must exist. Notice that the code also includes :debug, whose value is nil.

safe_reads.rb
config = { db: { host: "localhost", ports: [5432, 5433] }, debug: nil }
p config[:db][:host]
p config.dig(:db, :ports, 1)
p config.dig(:cache, :host)

begin
  config[:cache][:host]
rescue NoMethodError => e
  puts e.message
end

begin
  config.fetch(:timeout)
rescue KeyError => e
  puts e.message
end

p config.fetch(:timeout, 30)
p config.fetch(:debug)
p config.key?(:debug)
p config[:missing_key]

The output is "localhost", 5433, nil, undefined method '[]' for nil, key not found: :timeout, 30, nil, true and nil. fetch(:debug) returns nil because the value of :debug is nil, and key? says true, while [:missing_key] also gives nil. So never conclude that a key is absent just because [] returned nil; use key? when you need to know.

Transforming hashes and keeping their order

Hashes support select, reject, map and sort_by just like arrays, and the block receives |key, value|. select and reject return a new hash, map returns an array, transform_values changes the values and leaves the keys alone, and sort_by returns an array of [key, value] pairs, so add to_h when you want a hash back.

transform.rb
prices = { tea: 2.5, coffee: 3.0, milk: 1.2 }

p prices.transform_values { |price| (price * 1.1).round(2) }
p prices.select { |_name, price| price > 2 }
p prices.reject { |_name, price| price > 2 }
p prices.map { |name, price| "#{name}=#{price}" }
p prices.sort_by { |_name, price| price }.to_h
p prices.min_by { |_name, price| price }
p prices.sum { |_name, price| price }

prices.delete(:tea)
prices[:tea] = 2.6
p prices.keys

The values printed are {tea: 2.75, coffee: 3.3, milk: 1.32}, {tea: 2.5, coffee: 3.0}, {milk: 1.2}, ["tea=2.5", "coffee=3.0", "milk=1.2"], {milk: 1.2, tea: 2.5, coffee: 3.0}, [:milk, 1.2], 6.7 and [:coffee, :milk, :tea]. The last one proves insertion order: :tea was deleted and added again, so it moved to the end.

In real projects

Where this shows up in real projects

Hashes are the working format of the web. JSON.parse turns a JSON object into a hash (with string keys, or symbol keys when you pass symbolize_names: true), configuration loaded from YAML comes back as nested hashes, and Rails exposes request parameters through a hash-like params object. Reading such data safely with dig and fetch is a daily habit, because the shape of outside data is never guaranteed.

Counting and grouping reports use the patterns from this lesson: Hash.new(0) for how many orders per status, group_by or a Hash.new with a block for lists of orders per customer, and transform_values to turn counts into percentages. Memoization is another common use: cache = Hash.new { |hash, id| hash[id] = load_user(id) } computes each user once and remembers the answer.

Common mistakes

Common mistakes

1. Mixing string and symbol keys

Reading { name: "Aung" } with user["name"] gives nil because the key :name is not the key "name". Choose symbols for fixed fields and use them consistently; parse JSON with symbolize_names: true, or stay with string keys all the way.

2. Using Hash.new([])

With Hash.new([]), h[:a] << 1 pushes into one array shared by every key, and strangely h itself still prints as an empty {}. Use the block form, Hash.new { |hash, key| hash[key] = [] }.

3. Chaining [] through nil

In config[:cache][:host], a nil config[:cache] raises NoMethodError (undefined method '[]' for nil). config.dig(:cache, :host) just returns nil. When the key must exist, use fetch and let it fail immediately.

4. Adding keys while iterating

Adding a new key inside a loop such as h.each { |k, v| h[:b] = 2 } raises RuntimeError (can't add a new key into hash during iteration); updating an existing key is allowed. Collect the changes first and apply them after the loop, or build a new hash.

5. Treating a nil value as a missing key

{ debug: nil }[:debug] and {}[:debug] both give nil, yet one has the key and the other does not. When the difference matters, ask with key? or read with fetch.

Best practices

Best practices

  • Use symbol keys consistently for fixed fields and convert key style at the boundary where outside data arrives.
  • Use fetch when a key must exist, because [] answers nil and lets the mistake surface later.
  • Count with Hash.new(0) and collect lists with the block form to avoid a shared default.
  • Freeze config hashes that should not change, and call to_h to turn results back into a hash.

Mini challenge

Mini challenge: an HTTP status report

Count a list of status codes from a server log and print a short report. Use Hash.new(0) to count, transform_values to compute percentages, and fetch with a default for a status that never appeared.

  • tally(items) returns a hash counting how often each item appears (use Hash.new(0))
  • percentages(counts) returns a new hash with each count as a percentage rounded to one decimal (use transform_values)
  • most_common(counts) returns the key that appears most often (max_by)
  • Print the count for the missing status 418 with fetch(418, 0)
status_report.rb
def tally(items)
  # TODO: count each item with Hash.new(0)
end

def percentages(counts)
  # TODO: a new hash of percentages, rounded to 1 decimal (transform_values)
end

def most_common(counts)
  # TODO: the key with the highest count (max_by)
end

statuses = [200, 404, 200, 500, 200, 404, 301]
# TODO: print the count of 200, the most common status, the count of 418
# and the share of 404

Expected: 200 x3 most common: 200 418 count: 0 404 share: 28.6%

Show hint

The percentage is count * 100.0 / total, with total from counts.values.sum; writing 100.0 avoids integer division. max_by yields [key, value] pairs, so take the key with .first.

Show solution
status_report.rb
def tally(items)
  counts = Hash.new(0)
  items.each { |item| counts[item] += 1 }
  counts
end

def percentages(counts)
  total = counts.values.sum
  counts.transform_values { |count| (count * 100.0 / total).round(1) }
end

def most_common(counts)
  counts.max_by { |_status, count| count }.first
end

statuses = [200, 404, 200, 500, 200, 404, 301]
counts = tally(statuses)
shares = percentages(counts)

puts "200 x#{counts[200]}"
puts "most common: #{most_common(counts)}"
puts "418 count: #{counts.fetch(418, 0)}"
puts "404 share: #{shares[404]}%"

Quick quiz 1 / 3

Given user = { name: "Aung" }, what does user["name"] return?

Quick quiz 2 / 3

After counts = Hash.new([]), counts[:a] << 1 and counts[:b] << 2, what does counts[:c] return?

Quick quiz 3 / 3

Which call returns 30 when :timeout is missing and never raises an error?

What to remember

  • A hash stores key: value pairs in insertion order, and a symbol key is not the same as a string key.
  • [] gives nil for a missing key, fetch raises KeyError (or returns a default), and dig reads nested data safely.
  • Hash.new(0) gives a counter, while Hash.new([]) shares one array, so use the block form for lists.
  • Transform hashes with select, reject, map, transform_values and sort_by.to_h; Ruby 3.4 and later print them as {name: "x"}.

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Hashes | Thuta Learning