Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert multidimensional array to Hash in Ruby [closed]

Tags:

arrays

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

{'abc'=>[{'xyz'=>'1.1'},{'xyz'=>'1.2'}],'def'=>[{'lmn'=>'3.14'}]}

What's the best way to do this?

like image 405
Makoto Taguchi Avatar asked May 29 '26 01:05

Makoto Taguchi


1 Answers

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"}]}
like image 175
Ilya Avatar answered May 30 '26 16:05

Ilya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!