Created
October 6, 2011 00:17
-
-
Save agius/1266143 to your computer and use it in GitHub Desktop.
Useful methods for ruby hashes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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