Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Ruby hashes to arrays

I have a Hash which is of the form {:a => {"aa" => 11,"ab" => 12}, :b => {"ba" => 21,"bb" => 22}}

How do i convert it to the form {:a => [["aa",11],["ab",12]],:b=>[["ba",21],["bb",22]]}

like image 978
Aditya Manohar Avatar asked Jan 04 '11 08:01

Aditya Manohar


2 Answers

If you want to modify the original hash you can do:

hash.each_pair { |key, value| hash[key] = value.to_a }

From the documentation for Hash#to_a

Converts hsh to a nested array of [ key, value ] arrays.

h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }

h.to_a #=> [["c", 300], ["a", 100], ["d", 400]]

like image 115
mikej Avatar answered Sep 17 '22 15:09

mikej


Here is another way to do this :

hsh = {:a => {"aa" => 11,"ab" => 12}, :b => {"ba" => 21,"bb" => 22}}
hsh.each{|k,v| hsh[k]=*v}
# => {:a=>[["aa", 11], ["ab", 12]], :b=>[["ba", 21], ["bb", 22]]}
like image 21
Arup Rakshit Avatar answered Sep 21 '22 15:09

Arup Rakshit