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
{'abc'=>[{'xyz'=>'1.1'},{'xyz'=>'1.2'}],'def'=>[{'lmn'=>'3.14'}]}
What's the best way to do this?
You can use each_with_object:
accumulator = Hash.new { |k,v| k[v] = [] }
input.each_with_object(accumulator) {|(f, s), memo| memo[f] << Hash[*s] }
#=> {"abc"=>[{"xyz"=>"1.1"}, {"xyz"=>"1.2"}], "def"=>[{"lmn"=>"3.14"}]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With