Skip to content

Instantly share code, notes, and snippets.

@steveevers
Created November 15, 2017 18:59
Show Gist options
  • Save steveevers/9d584aed053b9b31467101807462a94c to your computer and use it in GitHub Desktop.
Save steveevers/9d584aed053b9b31467101807462a94c to your computer and use it in GitHub Desktop.
Depth first recursive versions of Hash::except
class Hash
def except_nested(key)
r = Marshal.load(Marshal.dump(self))
r.except_nested!(key)
end
def except_nested!(key)
self.except!(key)
self.each do |_, v|
v.except_nested!(key) if v.is_a?(Hash)
end
end
end
@guilhermegazzinelli
Copy link

In the case that removing keys inside array is needed:

class Hash
  def except_nested(key)
    r = Marshal.load(Marshal.dump(self))
    r.except_nested!(key)
  end

  def except_nested!(key)
    self.reject!{|k, v|k == key}
    self.each do |_, v|
      v.except_nested!(key) if v.is_a?(Hash)
      v.map!{|obj| obj.except_nested!(key) if obj.is_a?(Hash)} if v.is_a?(Array)
    end
  end
end

The except! was replaced by reject, since the first is exclusive for newer ruby verions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment