Skip to content

Instantly share code, notes, and snippets.

@tischler
Created January 27, 2015 09:35
Show Gist options
  • Save tischler/d44a3dc4d2bccd02238b to your computer and use it in GitHub Desktop.
Save tischler/d44a3dc4d2bccd02238b to your computer and use it in GitHub Desktop.
Deep Delete Via String Path
hash = { :a =>
{
:a => { :a => "foo", :b => "bar" },
:b => { :a => "foo", :c => "DELETEME" }
},
:b => {
:a => { :a => "foo", :b => "bar" },
:b => { :a => "foo", :c => "baz" }
},
:c => {
:a => { :a => "foo", :b => "bar" },
:b => { :a => "foo", :c => "baz" }
}
}
require 'pp'
pp hash
class Hash
def deep_delete(path)
begin
path = path.split '.'
leaf = path.pop
path.inject(self) { |memo, elem| memo[elem.to_sym] }.delete(leaf.to_sym)
self
rescue
self
end
end
end
pp hash.deep_delete("a.b.c")
.deep_delete("d.e.f")
.deep_delete("a.a.a")
.deep_delete("c.c.c")
.deep_delete("timtischler@kaleo")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment