Convert Ruby array of tuples into a hash given an array of keys?

This gets you the desired result.

hash = {}

array.each do |element|
  i = array2.index{ |x| x[0] == element }
  hash[element] = array2[i] unless i.nil?
end

Paired Tuples to Hash Example

fruit_values = [
  ['apple', 10],
  ['orange', 20],
  ['lemon', 5]
]

fruit_values.to_h
# => {"apple"=>10, "orange"=>20, "lemon"=>5} 

I decided I would leave this answer here for anyone looking to convert paired tuples into a hash.

Although it is slightly different from the question, this is where I landed on my Google search. It also matched up a bit with the original question due to the array of keys being already in the tuples. This also doesn't put the key into the value which the original question wanted, but I honestly wouldn't duplicate that data.


If the order of the mapping between the key and pairs should be based on the first element in array2, then you don't need array at all:

array2 = [
  ["apple", "good taste", "red"],
  ["lemon" , "no taste", "yellow"],
  ["orange", "bad taste", "orange"]
]

map = Hash[ array2.map{ |a| [a.first,a] } ]
p map
#=> {
#=>   "apple"=>["apple", "good taste", "red"],
#=>   "lemon"=>["lemon", "no taste", "yellow"],
#=>   "orange"=>["orange", "bad taste", "orange"]
#=> }

If you want to use array to select a subset of elements, then you can do this:

# Use the map created above to find values efficiently
array = %w[orange lemon]
hash  = Hash[ array.map{ |val| [val,map[val]] if map.key?(val) }.compact ]
p hash
#=> {
#=>   "orange"=>["orange", "bad taste", "orange"],
#=>   "lemon"=>["lemon", "no taste", "yellow"]
#=> }

The code if map.key?(val) and compact ensures that there is not a problem if array asks for keys that are not present in array2, and does so in O(n) time.

Tags:

Arrays

Ruby