Hash#to_a

hash.to_a
Returns: Array · Added in v1.8 · Updated March 16, 2026 · Hash Methods
ruby stdlib hash conversion

Hash#to_a converts a hash to a nested array where each element is a two-element array containing a key-value pair. This method is useful when you need to work with hashes in contexts that expect arrays, or when performing array-based transformations.

Syntax

hash.to_a

Examples

Basic conversion

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

user.to_a
# => [[:name, "Alice"], [:age, 30], [:city, "London"]]

Working with the result

scores = { alice: 95, bob: 87, charlie: 92 }

# Transpose back to hash
scores.to_a.to_h
# => { alice: 95, bob: 87, charlie: 92 }

Sorting by keys or values

data = { z: 1, a: 3, m: 2 }

# Sort by key
data.to_a.sort
# => [[:a, 3], [:m, 2], [:z, 1]]

# Sort by value
data.to_a.sort_by { |key, value| value }
# => [[:z, 1], [:m, 2], [:a, 3]]

Filtering and transforming

config = { host: "localhost", port: 3000, ssl: true, debug: false }

# Keep only string values
config.to_a.select { |key, val| val.is_a?(String) }
# => [[:host, "localhost"]]

# Transform to strings
config.to_a.map { |key, val| "#{key}=#{val}" }
# => ["host=localhost", "port=3000", "ssl=true", "debug=false"]

Building hashes from arrays

# Create hash from key-value pair arrays
pairs = [[:name, "Bob"], [:age, 25], [:city, "NYC"]]

pairs.to_h
# => { name: "Bob", age: 25, city: "NYC" }

# This is essentially what to_a does in reverse
{ a: 1, b: 2 }.to_a.to_h
# => { a: 1, b: 2 }

Common Patterns

Iteration with index

hash = { first: "a", second: "b", third: "c" }

hash.to_a.each_with_index do |(key, value), index|
  puts "#{index}: #{key} => #{value}"
end
# 0: first => a
# 1: second => b
# 2: third => c

Grouping and partitioning

data = { a: 1, b: 2, c: 3, d: 4, e: 5 }

even, odd = data.to_a.partition { |k, v| v.even? }
# even: [[:b, 2], [:d, 4]]
# odd:  [[:a, 1], [:c, 3], [:e, 5]]

# Convert back to hashes
even.to_h
# => { b: 2, d: 4 }

Converting to nested arrays for JSON

hash = { users: [{ name: "Alice" }, { name: "Bob" }] }

# Sometimes needed for specific JSON serialization
hash.to_a
# => [[:users, [{ name: "Alice" }, { name: "Bob" }]]]

Edge Cases

Empty hash

{}.to_a
# => []

Single key-value pair

{ key: "value" }.to_a
# => [[:key, "value"]]

Mixed key types

{ "string" => 1, :symbol => 2, 3 => 3 }.to_a
# => [["string", 1], [:symbol, 2], [3, 3]]

Hash with array values

{ items: [1, 2, 3], tags: %w[a b] }.to_a
# => [[:items, [1, 2, 3]], [:tags, ["a", "b"]]]

Performance Notes

Hash#to_a creates a new array and does not modify the original hash. For very large hashes, be aware that this conversion allocates additional memory proportional to the hash size.

If you only need to iterate over key-value pairs without converting, consider using Hash#each or Hash#each_pair instead, which are more memory-efficient.

See Also