Aditya Manohar
Aditya Manohar

Reputation: 2274

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

Upvotes: 11

Views: 40365

Answers (3)

mikej
mikej

Reputation: 66263

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

Upvotes: 28

umar
umar

Reputation: 4389

hash.collect {|a, b|  [a, hash[a].collect {|c,d| [c,d]}] }.collect {|e,f| [e => f]}

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118271

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

Upvotes: 4

Related Questions