简体   繁体   中英

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

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

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]]}
hash.collect {|a, b|  [a, hash[a].collect {|c,d| [c,d]}] }.collect {|e,f| [e => f]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM