Ruby: Deleting all instances of a particular key from hash of hashes
ruby
Solution
def f x
x.inject({}) do |m, (k, v)|
v = f v if v.is_a? Hash # note, arbitrarily recursive
m[k] = v unless k == 'inner'
m
end
end
p f h
Update: slightly improved...
def f x
x.is_a?(Hash) ? x.inject({}) do |m, (k, v)|
m[k] = f v unless k == 'inner'
m
end : x
end
Problem
I have a hash like ``` h = {1 => {"inner" => 45}, 2 => {"inner" => 46}, "inner" => 47} ``` How do I delete every pair that contains the key "inner"? You can see that some of the "inner" pairs appear directly in `h` while others appear in pairs in `h` Note that I only want to delete the "inner" pairs, so if I call my mass delete method on the above hash, I should get ``` h = {1 => {}, 2 => {}} ``` Since these pairs don't have a key == "inner"