10

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]]}

shingara
  • 46,608
  • 11
  • 99
  • 105
Aditya Manohar
  • 2,204
  • 1
  • 17
  • 20
  • If you're working with multi-level hashes and you want to flatten them check out my HashModel gem: https://rubygems.org/gems/hashmodel and you can get the source on github: https://github.com/mikbe/hashmodel –  Jan 04 '11 at 20:42

3 Answers3

28

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]]

Jan Papenbrock
  • 1,037
  • 1
  • 11
  • 24
mikej
  • 65,295
  • 17
  • 152
  • 131
4

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]]}
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
0
hash.collect {|a, b|  [a, hash[a].collect {|c,d| [c,d]}] }.collect {|e,f| [e => f]}
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
umar
  • 4,309
  • 9
  • 34
  • 47