Skip to content

Instantly share code, notes, and snippets.

@winfred
Created March 24, 2012 17:28
Show Gist options
  • Save winfred/2185384 to your computer and use it in GitHub Desktop.
Save winfred/2185384 to your computer and use it in GitHub Desktop.
Unobtrusive Ruby Hash dot access
class Hash
class NoKeyOrMethodError < NoMethodError; end
def method_missing(method,*args)
m = method.to_s
string_key = m.gsub(/=$/,'')
sym_key = string_key.to_sym
if self.has_key? string_key
m.match(/=$/) ? self.send("[#{string_key}]=", *args) : self[string_key]
elsif self.has_key? sym_key
m.match(/=$/) ? self.send("[#{sym_key}]=", *args) : self[sym_key]
else
raise NoKeyOrMethodError
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment