How to Convert an Array to a Hash in Ruby

What is the best way to convert an array to a hash in Ruby

NOTE: For a concise and efficient solution, please see Marc-André Lafortune's answer below.

This answer was originally offered as an alternative to approaches using flatten, which were the most highly upvoted at the time of writing. I should have clarified that I didn't intend to present this example as a best practice or an efficient approach. Original answer follows.


Warning! Solutions using flatten will not preserve Array keys or values!

Building on @John Topley's popular answer, let's try:

a3 = [ ['apple', 1], ['banana', 2], [['orange','seedless'], 3] ]
h3 = Hash[*a3.flatten]

This throws an error:

ArgumentError: odd number of arguments for Hash
from (irb):10:in `[]'
from (irb):10

The constructor was expecting an Array of even length (e.g. ['k1','v1,'k2','v2']). What's worse is that a different Array which flattened to an even length would just silently give us a Hash with incorrect values.

If you want to use Array keys or values, you can use map:

h3 = Hash[a3.map {|key, value| [key, value]}]
puts "h3: #{h3.inspect}"

This preserves the Array key:

h3: {["orange", "seedless"]=>3, "apple"=>1, "banana"=>2}

Converting array to hash (Ruby)

I'm a beginner too, so this may be a little inefficient, but this is how I would explain it (there are simpler methods I'm sure, but since you mentioned this is for a class, I thought I'd explain in long form):

hash={}

some_array.each do |item|
hash[item[0]] = item[1]
end

Just to explain that a bit, I start by creating an empty hash that I will use later.

Then I cycle through some_array using the each method. This assigns each element in some_array to the variable item. Given that some_array is a nested array (which basically means that it is an array of arrays), the item variable will take the value of the inner arrays - for example, item = [:a, 123].

Then we can access each element within item when creating the hash. Following the same example I gave earlier item[0] == :a and item[1] == 123.

Then I use some shorthand when creating hashes - i.e. hash[key] = value. In this case, I want the key to be :a (which is item[0]) and the value to be 123 (which is item[1]). So I can use hash[item[0]] = item[1].

Hope that helped!

Ruby convert an Array to Hash values with specific keys

You can use #zip

your_array = ["12", "21", "1985"]
keys = ['month', 'day', 'year']
keys.zip(your_array).to_h

How to convert an array to a hash with specified common values

There are many ways, e.g.:

arr.zip([{}] * arr.size).to_h

or (the latter, thx @Stefan, is not probably what you wanted, since it will share one hash for all keys):

arr.product([{}]).to_h

How to convert an array to a hash using Mongoid Pipeline?

Use $map to map your array from ['v1', 'v2', 'v3'] to [['v1', true], ['v2', true], ['v3', true]], then use https://docs.mongodb.com/manual/reference/operator/aggregation/arrayToObject/ to convert that to a hash.

How to convert an array of ids to array of hash with a key in ruby?

Anything like this?

array.map { |id| Hash[:id, id] }

the same with hash literal

array.map { |id| { id: id } }


Related Topics



Leave a reply



Submit