How to Work with Hashes in Ruby
Hashes are one of the most versatile data structures in Ruby. This cookbook covers practical recipes for common Hash operations.
Creating Hashes with Default Values
Problem
You need a hash that returns a default value when accessing a missing key.
Solution
scores = Hash.new(0)
scores[:alice] = 95
puts scores[:bob] # => 0
user_data = Hash.new do |hash, key|
hash[key] = { name: "Unknown" }
end
Merging Hashes
Problem
You need to combine multiple hashes.
Solution
defaults = { theme: "dark", language: "en" }
user_prefs = { theme: "light" }
merged = defaults.merge(user_prefs)
puts merged # => {:theme=>"light", :language=>"en"}
config = { env: "development" }
config.merge!(defaults)
Iterating Over Hashes
Problem
You need to loop through a hash.
Solution
inventory = { apples: 5, bananas: 3 }
inventory.each { |fruit, count| puts "#{fruit}: #{count}" }
inventory.each_key { |fruit| puts fruit }
inventory.each_value { |count| puts count }
Converting to Arrays
Problem
You need keys, values, or pairs as arrays.
Solution
person = { name: "Alice", age: 30 }
keys = person.keys
values = person.values
pairs = person.to_a
Hash Transformation
problem
You need to extract or transform hash keys and values.
Solution
user = { id: 1, name: "Bob", email: "bob@example.com" }
public_info = user.slice(:name, :email)
upcased = user.transform_keys { |k| k.to_s.upcase }
stringified = user.transform_values(&:to_s)
why these hash recipes stay useful
These patterns cover the most common hash jobs in small Ruby programs: default lookup behavior, merging settings, iterating through entries, and reshaping the data when the next step wants a different view. The idea is to keep the hash work close to the need that created it, rather than building a larger abstraction too early. That makes the examples easy to reuse in scripts, services, and small libraries.
The same shape also makes the code easier to revise later. If the defaults change, the merge order changes, or the output format needs a small adjustment, each recipe shows the exact place where that decision lives. That is usually enough structure for a cookbook: short examples, a clear reason for each one, and a simple path from input to result.
Summary
These hash operations cover most everyday tasks. Remember that most transformation methods return new hashes.