Ruby Hashes
A hash stores key–value pairs, like a dictionary: you look up a value by its key. Keys can be any object, but symbols and strings are the most common. Hashes remember the order in which keys were inserted.
Creating hashes
book = {title: "Dune", author: "Frank Herbert", year: 1965}
prices = {"apple" => 0.5, "melon" => 2.25}
empty = {}
p book
p prices
p empty
p book.class{title: "Dune", author: "Frank Herbert", year: 1965}
{"apple" => 0.5, "melon" => 2.25}
{}
Hash
title: "Dune"is shorthand for a symbol key::title => "Dune".- Other kinds of keys use the "hash rocket"
=>.
Note: Ruby 3.4 changed how hashes are printed.
p bookshows{title: "Dune", ...}; versions before 3.4 printed{:title=>"Dune", ...}. The hashes themselves work the same.
Reading values
book = {title: "Dune", author: "Frank Herbert", year: 1965}
p book[:title]
p book[:pages]
p book.fetch(:year)
p book.fetch(:pages, 0)
p book.key?(:author)
p book.value?(1965)
p book.dig(:title)
begin
book.fetch(:pages)
rescue KeyError => e
puts "KeyError: #{e.message}"
end"Dune"
nil
1965
0
true
true
"Dune"
KeyError: key not found: :pages
[] returns nil for a missing key; fetch raises KeyError (or returns the default you give it). Use fetch when a missing key would be a bug.
Adding, changing and removing
cart = {}
cart[:apple] = 3
cart[:bread] = 1
cart[:apple] += 2
p cart
removed = cart.delete(:bread)
p removed
p cart
cart.store(:milk, 2)
p cart.size
cart.clear
p cart.empty?{apple: 5, bread: 1}
1
{apple: 5}
2
true
Default values
A hash can return a default for missing keys instead of nil. Counting things becomes very easy:
counts = Hash.new(0)
"mississippi".each_char { |c| counts[c] += 1 }
p counts
groups = Hash.new { |hash, key| hash[key] = [] }
%w[ant bee cat cow ape].each { |w| groups[w[0]] << w }
p groups{"m" => 1, "i" => 4, "s" => 4, "p" => 2}
{"a" => ["ant", "ape"], "b" => ["bee"], "c" => ["cat", "cow"]}
Tip: Use
Hash.new { |h, k| h[k] = [] }, notHash.new([]), for a hash of lists. The latter shares one array between all keys.
Iterating
population = {tokyo: 37.4, delhi: 32.9, shanghai: 29.2}
population.each do |city, millions|
puts "#{city.to_s.capitalize}: #{millions}M"
end
p population.keys
p population.values
p population.to_a.firstTokyo: 37.4M
Delhi: 32.9M
Shanghai: 29.2M
[:tokyo, :delhi, :shanghai]
[37.4, 32.9, 29.2]
[:tokyo, 37.4]
Transforming and filtering
stock = {apples: 12, pears: 0, plums: 7, figs: 0}
p stock.select { |_, qty| qty > 0 }
p stock.reject { |_, qty| qty > 0 }.keys
p stock.transform_values { |q| q * 2 }
p stock.transform_keys(&:to_s)
p stock.map { |k, v| "#{k}=#{v}" }.join("&")
p stock.sort_by { |_, v| -v }.first(2).to_h
p stock.min_by { |_, v| v }
p stock.sum { |_, v| v }
p stock.count { |_, v| v.zero? }
p stock.filter_map { |k, v| k if v > 5 }{apples: 12, plums: 7}
[:pears, :figs]
{apples: 24, pears: 0, plums: 14, figs: 0}
{"apples" => 12, "pears" => 0, "plums" => 7, "figs" => 0}
"apples=12&pears=0&plums=7&figs=0"
{apples: 12, plums: 7}
[:pears, 0]
19
2
[:apples, :plums]
Merging
defaults = {theme: "light", font_size: 14, sidebar: true}
user_prefs = {theme: "dark", font_size: 16}
settings = defaults.merge(user_prefs)
p settings
totals = {a: 1, b: 2}.merge({b: 10, c: 3}) { |key, old, new| old + new }
p totals
p settings.slice(:theme, :sidebar)
p settings.except(:sidebar){theme: "dark", font_size: 16, sidebar: true}
{a: 1, b: 12, c: 3}
{theme: "dark", sidebar: true}
{theme: "dark", font_size: 16}
When keys clash, merge keeps the value from the argument, unless you pass a block to decide.
Nested hashes
config = {
db: {host: "localhost", port: 5432},
cache: {enabled: false},
}
p config[:db][:port]
p config.dig(:cache, :enabled)
p config.dig(:mail, :from)5432
false
nil
dig walks through nested hashes and returns nil as soon as a level is missing, instead of crashing.
Test yourself
What does {a: 1}[:b] return?
- 0
- nil
- KeyError
- false
What does Hash.new(0) do?
- Creates a hash with one key 0
- Creates a hash whose missing keys return 0
- Creates a hash that can hold 0 items
- Raises an error
In {x: 1}.merge({x: 2}), what is the value of :x?
- 1
- 2
- 3
- [1, 2]