In Ruby, a Hash refers to a collection of key-value pairs. It is closely similar to an array in the sense that it can store multiple related values, but the indexing is done via keys rather than integers. If you are familiar with Python programming languages, think of Ruby Hashes as Python dictionaries.
On the other hand, an array refers to an ordered collection of values. You can think of an array as a list of items with a specific index or position for each item.
You may encounter such instances where you need to expand an index to a Ruby Hash. This makes it easy to map a given set of values in an array to a corresponding dictionary-like format.
This tutorial covers various methods to convert a given Ruby array into a Hash.
Example Array
To demonstrate how we can convert an array to a Hash in Ruby, we will work with the example array which is provided in the following:
In this case, we wish to convert the array into a Hash where the numerical value acts as the key, and the string values are the value of the Hash.
Converting an Array to Hash Using the To_H Method
In the latest Ruby versions, we have access to the to_h method that allows us to convert a two-dimensional array into a Ruby Hash.
Hence, we need first to convert the one-dimensional array into a two-dimensional array.
We can accomplish this using the each_slice method. This method is defined in the Ruby Enumerable module which is included in the Array class. It allows us to iterate over the elements of an array in slices of a given size.
We can use this method as demonstrated in the following code:
=> #<Enumerator: ...>
This returns an enumerator object which we can convert into an array using the to_a method as shown in the following:
=> [[1, "MySQL"], [2, "PostgreSQL"], [3, "SQLite"]]
This should give us a two-dimensional array, as demonstrated previously.
Finally, we can convert the values into a has as shown in the following:
The resulting Hash is as follows:
Converting an Array to Hash Using the Hash::[] Method
The ::[] notation in the Ruby Hash class allows us to return a new Hash with the provided values.
To convert an array to a Hash using this method, we can use the following command:
=> {"1"=>"MySQL", "2"=>"PostgreSQL", "3"=>"SQLite"}
This should return a new Hash without needing to convert the array into a two-dimensional array.
Conclusion
We discussed how you could use the Array#to_h method and Hash::[] methods to convert an array to a Hash in the Ruby programming language.