开发者

Ruby: This "Double dimensional hash" requires processing

开发者 https://www.devze.com 2023-01-06 07:17 出处:网络
I have this: h = {1 => { 1 => {:a => \"x\", :b => \"y\", :c =开发者_开发问答> \"z\"},

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 ?


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


(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"}
}
0

精彩评论

暂无评论...
验证码 换一张
取 消