How to Work with Hashes in Ruby
· 2 min read · Updated March 12, 2026 · beginner
ruby hash cookbook
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)
Summary
These hash operations cover most everyday tasks. Remember that most transformation methods return new hashes.