Created
March 24, 2012 17:28
-
-
Save winfred/2185384 to your computer and use it in GitHub Desktop.
Unobtrusive Ruby Hash dot access
This file contains hidden or 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 | |
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