Skip to content

Instantly share code, notes, and snippets.

@agius
Created October 6, 2011 00:17
Show Gist options
  • Save agius/1266143 to your computer and use it in GitHub Desktop.
Save agius/1266143 to your computer and use it in GitHub Desktop.
Useful methods for ruby hashes
class Hash
# gets hash-nested values, returns nil if any key is missing
def dig(*path)
path.inject(self) do |location, key|
location.respond_to?(:keys) ? location[key] : nil
end
end
# Deletes key from self and returns self
def kill(key)
delete(key)
self
end
# Returns self with all specified keys removed
def kill_all(keys)
keys.each {|k| kill(k) }
self
end
# Returns a copy of self with key removed
def remove(key)
self.dup.kill(key)
end
# Returns a new array with all specified keys removed
def remove_all(keys)
self.dup.kill_all(keys)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment