Hash#each_pair

hash.each_pair { |key, value| block } -> hash
Returns: hash · Updated March 16, 2026 · Hash Methods
ruby hash iteration enumerable

Hash#each_pair is an alias for Hash#each. Both methods iterate over key-value pairs and yield each key and value to the block. The method returns the original hash, making it chainable with other Enumerable methods.

Basic Usage

user = { name: "Alice", age: 30, city: "London" }

user.each_pair do |key, value|
  puts "#{key}: #{value}"
end
# Output:
# name: Alice
# age: 30
# city: London

The block receives two parameters: the key and the value. Both are available for use inside the block.

Destructuring in Blocks

Ruby 2.7+ supports block parameter destructuring, which lets you unpack the key-value pair directly:

data = { a: 1, b: 2, c: 3 }

data.each_pair do |(key, value)|
  puts "#{key} = #{value}"
end
# Output:
# a = 1
# b = 2
# c = 3

This syntax is particularly useful when working with each_with_object or when you prefer explicit unpacking.

each vs each_pair

Hash#each and Hash#each_pair are functionally identical. Ruby provides both for historical reasons and developer preference. Some codebases use each_pair to explicitly indicate that both keys and values are being processed, while others prefer the shorter each form.

# These produce identical results
hash = { x: 1, y: 2 }

hash.each { |k, v| puts "#{k}: #{v}" }
hash.each_pair { |k, v| puts "#{k}: #{v}" }

Both methods return the original hash, so you can chain them:

result = { a: 1, b: 2, c: 3 }
  .each_pair.select { |k, v| v > 1 }
  .to_h

# => { b: 2, c: 3 }

With Enumerable

Since Hash includes Enumerable, you can use each_pair in combination with other Enumerable methods:

scores = { alice: 95, bob: 82, carol: 78 }

high_scorers = scores
  .each_pair
  .select { |_, score| score > 80 }
  .map { |name, _| name }

# => [:alice, :bob]

Return Value

Each_pair returns the original hash, not the block’s return value. If you need to collect results, consider using map or each_with_object instead:

hash = { a: 1, b: 2, c: 3 }

# Returns hash, not the summed value
returned = hash.each_pair { |k, v| puts "#{k}: #{v}" }
# => { a: 1, b: 2, c: 3 }

# Use each_with_object for accumulation
sum = hash.each_pair.with_object(0) { |(k, v), acc| acc + v }
# => 6

Ruby Version Notes

Hash#each_pair has been available since Ruby 1.8. Block parameter destructuring requires Ruby 2.7 or later. Ruby 3.x maintains full backward compatibility with all existing behavior.

See Also

  • hash-each — The primary iteration method, identical to each_pair
  • hash-merge — Combine hashes with merge
  • hash-select — Filter hash entries based on conditions