In certain instances, the need to convert an array to a hash and vice versa comes up. In this guide, we shall discuss how you can convert an array to a hash in Ruby.
#1 – Using the each method
Suppose you have an array you wish to convert to a string where the key of the hash is the array element, and the value of the hash is the array’s element + 10.
To do this, we can use the each method to iterate each item in the array and convert it into a string.
my_hash = {}
var.each do |i|
my_hash[i] = i+10
end
puts my_hash
The above example will convert each item in the array to a hash key paired with its value.
The resulting dictionary is as shown:
#2 – Using each_with_object
Ruby provides another method called each_with_object. The method executes the each method after creating a new object you can form from the array elements.
Example:
var.each_with_object({}) do |i, my_hash|
my_hash[i] = i+10
end
The functionality of the above example is similar to using the each method.
The resulting hash value is as:
To see how the function iterates over the items in the array and converts them to a hash, you can add a puts element inside the block as:
var.each_with_object({}) do |i, my_hash|
my_hash[i] = i+10
puts my_hash
end
If you run the code above, you should get a hierarchical view of the hash creation process.
#3 – Using the to_h method
The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs.
Example:
puts var.to_h
The method converts each nested array into key-value pairs.
The method also accepts a block. If any block is specified, the method returns the result of the block on each array element.
For example, the following is a method showing if the value is true or false.
puts var.to_h {|i| [i.even?, i]}
The resulting dictionary:
In closing
In this guide, we discussed how to convert an array to a hash using various methods.