0
0
RubyHow-ToBeginner · 2 min read

Ruby How to Convert Array to Hash with Examples

In Ruby, you can convert an array to a hash by using 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

Input[[:a, 1], [:b, 2]]
Output{:a=>1, :b=>2}
Input["apple", "banana"] with index as key
Output{0=>"apple", 1=>"banana"}
Input[]
Output{}
🧠

How to Think About It

To convert an array to a hash, first check if the array elements are pairs (two-item arrays). If yes, you can directly convert it using to_h. If not, decide how to create keys and values, then build the hash by assigning each key to its value.
📐

Algorithm

1
Check if the array contains pairs (arrays with two elements).
2
If yes, use the built-in method to convert directly to a hash.
3
If no, decide how to generate keys and values from the array elements.
4
Create an empty hash.
5
Loop through the array and assign keys and values to the hash.
6
Return the constructed hash.
💻

Code

ruby
array = [[:a, 1], [:b, 2]]
hash = array.to_h
puts hash

array2 = ["apple", "banana"]
hash2 = array2.each_with_index.to_h
puts hash2
Output
{:a=>1, :b=>2} {0=>"apple", 1=>"banana"}
🔍

Dry Run

Let's trace converting [[:a, 1], [:b, 2]] to a hash using to_h

1

Start with array

[[:a, 1], [:b, 2]]

2

Call to_h

Converts each pair to key-value in hash

3

Resulting hash

{:a=>1, :b=>2}

Array ElementHash KeyHash Value
[:a, 1]:a1
[:b, 2]:b2
💡

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

each_with_object
ruby
array = ["apple", "banana"]
hash = array.each_with_object({}).with_index { |(item, h), i| h[i] = item }
puts hash
Manually builds a hash with index keys; useful when array elements are not pairs.
map with to_h
ruby
array = ["apple", "banana"]
hash = array.map.with_index { |item, i| [i, item] }.to_h
puts hash
Creates pairs first, then converts to hash; clear and readable.

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.

ApproachTimeSpaceBest For
to_hO(n)O(n)Array of pairs, simple conversion
each_with_objectO(n)O(n)Custom key-value creation
map with to_hO(n)O(n)Readable pair creation before conversion
💡
Use to_h directly if your array contains pairs to convert it quickly to a hash.
⚠️
Trying to use to_h on an array that does not contain pairs will cause an error.