Ruby

Convert Array to Hash Ruby

Both arrays and dictionaries share a common trait in all major programming languages: they are both flexible and scalable data structures that help organize and refactor code.

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.

var = [1,2,3,4,5,6,7,8,9,10]

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:

{1=>11, 2=>12, 3=>13, 4=>14, 5=>15, 6=>16, 7=>17, 8=>18, 9=>19, 10=>20}

#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 = [1,2,3,4,5,6,7,8,9,10]

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:

{1=>11, 2=>12, 3=>13, 4=>14, 5=>15, 6=>16, 7=>17, 8=>18, 9=>19, 10=>20}

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 = [1,2,3,4,5,6,7,8,9,10]

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:

var = [[1,2], [3,4], [5,6]]

puts var.to_h

The method converts each nested array into key-value pairs.

{1=>2, 3=>4, 5=>6}

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.

var = [1,2]

puts var.to_h {|i| [i.even?, i]}

The resulting dictionary:

{false=>1, true=>2}

In closing

In this guide, we discussed how to convert an array to a hash using various methods.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list