Ruby Convert Array to Hash With Index as Key

1. Introduction

Ruby developers often face the need to convert arrays into hashes, especially when a transformation requires indexing array items. Creating a hash with indices as keys can provide quicker access to elements and enhance the manageability of the data. This blog post will guide you on converting an array into a hash, where each element's index within the array becomes the key in the hash.

2. Program Steps

1. Define the array to be converted.

2. Iterate over the array with indices.

3. Create a hash where each index-value pair from the array becomes a key-value pair in the hash.

3. Code Program

# Step 1: Define the array
array = ['apple', 'banana', 'cherry']
# Step 2 and 3: Iterate over the array with indices and create the hash
hash_with_indices = array.each_with_index.each_with_object({}) do |(element, index), hash|
  hash[index] = element
# Output the resulting hash
puts hash_with_indices


{0=>"apple", 1=>"banana", 2=>"cherry"}


1. array is the array of strings representing various fruits.

2. each_with_index is an enumerator that gives us the element along with its index.

3. each_with_object({}) is used here to iterate over the array while carrying an initially empty hash object which is populated with index-element pairs.

4. Inside the block, hash[index] = element sets the index as the key and the element as the value for the hash.

5. hash_with_indices then contains the resulting hash from this operation, mapping each element of the array to its index in the array.