Makoto Taguchi Makoto Taguchi - 9 months ago 30
Ruby Question

Convert multidimensional array to Hash in Ruby

I have input something like this:

input = [['abc',['xyz','1.1']], ['abc',['xyz','1.2']],['def',['lmn','3.14']]]

And I want to convert this to


What's the best way to do this?

Answer Source

One more way to do it:

input.inject({}) { |a, (k, v)| a.merge(k => [Hash[*v]]) { |_, o, n| o + n } }

It was pointed out by Ilya that merge! should be preferred over merge since it has better performance characteristics.