Skip to content

Instantly share code, notes, and snippets.

@rwilcox
Created June 22, 2009 01:29
Show Gist options
  • Save rwilcox/133754 to your computer and use it in GitHub Desktop.
Save rwilcox/133754 to your computer and use it in GitHub Desktop.
class Hash
# A better implementation of Hash#fetch, which will return a default
# parameter passed in, the result of the passed in block
# OR throw IndexError if the key is not in the hash
# fetch! is a version of this function that returns the name of the key that was
# not found in the hash.
# For a good detail of the Hash#fetch method see:
# <http://avdi.org/devblog/2009/03/16/go-fetch/>
def fetch!(key, default_value=nil, &block)
begin
if block_given?
self.fetch(key, &block)
else
if default_value
self.fetch(key, default_value)
else
self.fetch(key)
end
end
rescue IndexError => e
raise IndexError, "key '#{key}' not found"
end
end
end
def tests
t = {"a" => 1}
p t.fetch!("b", "something")
t.fetch!("b") {puts "no worries, mate!"}
t.fetch!("b")
end
tests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment