Sachin
Sachin

Reputation: 27

Convert Array of Hashes to a Hash

I'm trying to convert the following:

dep = [
      {id: 1, depen: 2},
      {id: 1, depen: 3},
      {id: 3, depen: 4},
      {id: 5, depen: 3},
      {id: 3, depen: 6}
]

Into a single hash:

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

I tried a solution I found on another question:

dep.each_with_object({}) { |g,h| h[g[:id]] = g[:dep_id] } 

However, the output removed elements and gave me:

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

where the last element is also incorrect.

Upvotes: 0

Views: 49

Answers (1)

max pleaner
max pleaner

Reputation: 26758

You cannot have a hash like {1=>2, 1=>3, 3=>4, 5=3, 3=>6}. All keys of a hash mst have be unique.

If you want to get a hash mapping each id to a list of dependencies, you can use:

result = dep.
  group_by { |obj| obj[:id] }.
  transform_values { |objs| objs.map { |obj| obj[:depen] } }

Or

result = dep.reduce({}) do |memo, val|
  memo[val[:id]] ||= []
  memo[val[:id]].push val[:depen]
  memo
end

which produce

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

Upvotes: 6

Related Questions