Ruby How to Convert Array to Hash with Examples
array.to_h if the array contains pairs, or by using array.each_with_object({}) { |item, hash| hash[key] = value } to build a hash manually.Examples
How to Think About It
to_h. If not, decide how to create keys and values, then build the hash by assigning each key to its value.Algorithm
Code
array = [[:a, 1], [:b, 2]] hash = array.to_h puts hash array2 = ["apple", "banana"] hash2 = array2.each_with_index.to_h puts hash2
Dry Run
Let's trace converting [[:a, 1], [:b, 2]] to a hash using to_h
Start with array
[[:a, 1], [:b, 2]]
Call to_h
Converts each pair to key-value in hash
Resulting hash
{:a=>1, :b=>2}
| Array Element | Hash Key | Hash Value |
|---|---|---|
| [:a, 1] | :a | 1 |
| [:b, 2] | :b | 2 |
Why This Works
Step 1: Using to_h on pairs
The to_h method converts an array of two-element arrays into a hash by using the first element as the key and the second as the value.
Step 2: Building hash manually
If the array elements are not pairs, you can use each_with_object({}) or each_with_index to assign keys and values explicitly.
Step 3: Result is a hash
The final output is a hash where each key maps to its corresponding value from the array.
Alternative Approaches
array = ["apple", "banana"] hash = array.each_with_object({}).with_index { |(item, h), i| h[i] = item } puts hash
array = ["apple", "banana"] hash = array.map.with_index { |item, i| [i, item] }.to_h puts hash
Complexity: O(n) time, O(n) space
Time Complexity
Converting an array to a hash requires visiting each element once, so it takes linear time proportional to the array size.
Space Complexity
A new hash is created with the same number of elements as the array, so space usage is also linear.
Which Approach is Fastest?
to_h is fastest for arrays of pairs because it is optimized internally. Manual methods add slight overhead but offer flexibility.
| Approach | Time | Space | Best For |
|---|---|---|---|
| to_h | O(n) | O(n) | Array of pairs, simple conversion |
| each_with_object | O(n) | O(n) | Custom key-value creation |
| map with to_h | O(n) | O(n) | Readable pair creation before conversion |
to_h directly if your array contains pairs to convert it quickly to a hash.to_h on an array that does not contain pairs will cause an error.