Skip to content

Instantly share code, notes, and snippets.

@sutetotanuki
Created July 25, 2012 04:52
Show Gist options
  • Select an option

  • Save sutetotanuki/3174469 to your computer and use it in GitHub Desktop.

Select an option

Save sutetotanuki/3174469 to your computer and use it in GitHub Desktop.
HashのkeyをGrabのような検索してHashの要素を消す。
class Hash
def delete_keys!(match_string)
keys = self.all_keys
keys.each do |key|
if File.fnmatch?(match_string, key, File::FNM_PATHNAME)
h = self
split_key = key.split("/")[1..-1]
split_key.each_with_index do |k, i|
break if i == split_key.length - 1
h = h[k]
end
h.delete(split_key.last)
end
end
end
def all_keys
keys = []
_all_keys("", self, keys)
keys
end
def _all_keys(context_key, obj, keys_store)
if obj.is_a?(Hash)
obj.each do |k,v|
_all_keys(context_key + "/" + k.to_s, v, keys_store)
end
else
keys_store << context_key;
end
end
end
a = { "a" => { "b" => { "c" => 1} }, "e" => { "f" => 1, "g" => 2 } }
a.delete_keys!("/a/**/c")
a.delete_keys!("/e/*")
p a #=> {"a"=>{"b"=>{}}, "e"=>{}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment