Ruby - Merge an Array into a Hash -
i have array looks this:
array = [[:foo, :bar], [:foo, :baz], [:baz, {a: 1, b: 2}], [:baz, {c: 1, d:2}]]
and need turn hash looks this:
{:foo =>[:bar, :baz], :baz => {a: 1, b: 2, c: 1, d: 2}}
this code have far:
def flatten(array) h = {} array.each_with_object({}) |(k, v), memo| if v.is_a?(hash) memo[k] = h.merge!(v) else # goes here? end end end
when used so:
flatten(array)
outputs:
{baz => {:a => 1, :b => 2, :c => 1, :d => 2}}
may please point me in right direction? appreciated.
def convert(arr) arr.each_with_object({}) |a,h| h[a.first] = case a.last when hash (h[a.first] || {}).update(a.last) else (h[a.first] || []) << a.last end end end convert array #=> {:foo=>[:bar, :baz], :baz=>{:a=>1, :b=>2, :c=>1, :d=>2}}
Comments
Post a Comment