Created
January 23, 2013 08:21
-
-
Save NIA/4603084 to your computer and use it in GitHub Desktop.
Javascript-like working with Hash in Ruby (HACK)
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
# Add javascript-like functionality to Hash: | |
# write hash.prop instead of hash['prop'] | |
# | |
# NB: Your keys must NOT be named like standard methods of Hash | |
# In such case, use normal notation, e.g. hash['key'] | |
# | |
# So it is kinda dangerous hack! | |
class Hash | |
def method_missing(meth, *args) | |
method = meth.to_s # Symbol -> String | |
if method.end_with? '=' | |
self[method.chop] = *args | |
else | |
self[method] | |
end | |
end | |
end | |
data = { 'alpha' => 1, 'beta' => 2 } | |
# Reading | |
puts data['alpha'] # => 1 | |
puts data.alpha # => 1 | |
# Writing | |
data['beta'] = 8 | |
puts data['beta'] # => 8 | |
data.beta = 10 | |
puts data.beta # => 10 | |
# Reading non-existing | |
puts data['gamma'].inspect # => nil | |
puts data.gamma.inspect # => nil | |
# Writing non-existing | |
data.gamma = 42 | |
puts data.gamma # 42 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment