11

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

1
  • If you're working with multi-level hashes and you want to flatten them check out my HashModel gem: rubygems.org/gems/hashmodel and you can get the source on github: github.com/mikbe/hashmodel Commented Jan 4, 2011 at 20:42

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @mikej. Worked like a charm, though I'd like to know what the difference between hash.each and hash.each_pair is ?
If you don't want to modify the original hash, you can use this: new_hash = hash.inject({}) { |h, (key, value)| h[key] = value.to_a; h }
@Aditya: If you want your block to get two parameters, use each_pair. If only for readability.
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]]}

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.