Ruby How to Convert Hash to Array with Examples
In Ruby, you can convert a hash to an array using
hash.to_a, which returns an array of key-value pairs as nested arrays.Examples
Input{a: 1, b: 2}
Output[[:a, 1], [:b, 2]]
Input{'x' => 10, 'y' => 20}
Output[['x', 10], ['y', 20]]
Input{}
Output[]
How to Think About It
To convert a hash to an array, think of each key-value pair as a small pair inside the hash. You want to collect all these pairs into a list (array) where each element is a two-item array containing the key and its value.
Algorithm
1
Get the input hash.2
Use the built-in method to convert the hash into an array of pairs.3
Return the resulting array.Code
ruby
hash = {a: 1, b: 2, c: 3}
array = hash.to_a
puts array.inspectOutput
[[:a, 1], [:b, 2], [:c, 3]]
Dry Run
Let's trace {a: 1, b: 2} through the code
1
Start with hash
{a: 1, b: 2}
2
Convert hash to array
[[:a, 1], [:b, 2]]
3
Print the array
[[:a, 1], [:b, 2]]
| Hash | Array |
|---|---|
| {a: 1, b: 2} | [[:a, 1], [:b, 2]] |
Why This Works
Step 1: Using <code>to_a</code> method
The to_a method on a hash converts it into an array where each element is a two-item array of key and value.
Step 2: Structure of output
Each key-value pair becomes an array like [key, value], so the whole hash becomes an array of these pairs.
Alternative Approaches
Using <code>map</code> to customize output
ruby
hash = {a: 1, b: 2}
array = hash.map { |k, v| [k, v] }
puts array.inspectThis is similar to <code>to_a</code> but allows you to change the output format if needed.
Extract keys and values separately
ruby
hash = {a: 1, b: 2}
keys = hash.keys
values = hash.values
puts keys.inspect
puts values.inspectThis gives two arrays: one of keys and one of values, useful if you want them separate.
Complexity: O(n) time, O(n) space
Time Complexity
Converting a hash to an array requires visiting each key-value pair once, so it takes linear time proportional to the number of pairs.
Space Complexity
The resulting array stores all pairs, so it uses extra space proportional to the hash size.
Which Approach is Fastest?
to_a is the fastest and simplest method; alternatives like map add flexibility but with similar performance.
| Approach | Time | Space | Best For |
|---|---|---|---|
| hash.to_a | O(n) | O(n) | Simple conversion to array of pairs |
| hash.map { |k,v| [k,v] } | O(n) | O(n) | Custom transformations during conversion |
| hash.keys and hash.values | O(n) | O(n) | Separate arrays of keys and values |
Use
hash.to_a for a quick and easy conversion of a hash to an array of pairs.Trying to convert a hash to a flat array without pairs, which loses the key-value relationship.