tags:

views:

36

answers:

2

I have this:

h = {  1 => { 1 => {:a => "x", :b => "y", :c => "z"}, 
              2 => {:a => "xx", :b => "yy", :c => "zz"}
             }, 
       2 => { 1 => {:a => "p", :b => "q", :c => "r"}, 
              2 => {:a => "pp", :b => "qq", :c => "rr"}
            }
    }

I want to get this:

result = {  1 => { 1 => {:a => "x"}, 
                   2 => {:a => "xx"}
             }, 
            2 => { 1 => {:a => "p"}, 
                   2 => {:a => "pp"}
            }
    }

What would be a nice way of doing this ?

+2  A: 

A single example can't really define your structure. For example, are hashes always 3 levels deep with hashes to be pruned at the level 3?

You can start with:

h.each{|k1,v1| v1.each{|k2, v2| v2.delete_if{|k3,v3| k3 != :a}}}
Mladen Jablanović
My hash is 3 levels deep so this is just perfect... Works perfect for my case... Thank You !
Shikher
+1  A: 

(Should really be a comment, but the code's hard to read that way)

If you're removing from the innermost hash all keys except :a, why not assign the value part of that hash directly to the hash that contains it?

result = {
  1 => { 1 => "x", 2 => "xx"}, 
  2 => { 1 => "p", 2 => "pp"}
}
Mike Woodhouse
Thanks for the tip Mike. That is actually looking much better...
Shikher
Hey... My actual problem was slightly different to what this is. I solved the problem using @Mladen's answer and I have got the final answer in the format you specified... :)
Shikher