Hash#each
hash.each { |key, value| block } -> hash hash (each, each_pair), object (each_with_object) · Updated March 13, 2026 · Hash Methods The Hash class provides three primary methods for iterating over key-value pairs: .each, .each_pair, and .each_with_object. Each serves a slightly different purpose depending on whether you need to modify the hash during iteration or accumulate a result in a separate object.
.each
The .each method iterates over each key-value pair and yields both to the block. It returns the original hash, making it chainable with other methods.
user = { name: "Alice", age: 30, city: "London" }
user.each do |key, value|
puts "#{key}: #{value}"
end
# Output:
# name: Alice
# age: 30
# city: London
You can also iterate over just keys or just values:
user.each_key { |key| puts key }
# name
# age
# city
user.each_value { |value| puts value }
# Alice
# 30
# London
.each_pair
The .each_pair method is identical to .each. Both iterate over key-value pairs and return the hash. Ruby provides both as aliases, though .each is more commonly used.
config = { theme: "dark", font_size: 14, auto_save: true }
config.each_pair do |key, value|
puts "#{key} = #{value}"
end
.each_with_object
The .each_with_object method differs significantly from .each and .each_pair. It takes an object as an argument and yields that object along with each key-value pair. The object persists across iterations and is returned at the end. This makes it useful for accumulating results without explicitly tracking external variables.
numbers = { a: 1, b: 2, c: 3, d: 4 }
sum = numbers.each_with_object(0) do |(key, value), accumulator|
accumulator + value
end
puts sum # => 10
Notice the destructuring syntax — you can unpack the key-value pair directly in the block parameters.
You can build arrays, hashes, or any object:
words = { first: "hello", second: "world", third: "ruby" }
uppercased = words.each_with_object({}) do |(key, value), result|
result[key] = value.upcase
end
# => { first: "HELLO", second: "WORLD", third: "RUBY" }
Choosing the Right Method
Use .each or .each_pair when you need to:
- Perform side effects (printing, logging)
- Chain methods on the hash itself
- Iterate without needing to accumulate a result
Use .each_with_object when you need to:
- Build a new data structure from the hash
- Avoid explicit variable mutation outside the block
- Create transformations in a functional style
Ruby Version Notes
All three methods are available in Ruby 1.8 and later. The destructuring syntax requires Ruby 2.7 or later. Ruby 3.x maintains full backward compatibility.