Skip to content

Instantly share code, notes, and snippets.

@NIA
Created January 23, 2013 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NIA/4603084 to your computer and use it in GitHub Desktop.
Save NIA/4603084 to your computer and use it in GitHub Desktop.
Javascript-like working with Hash in Ruby (HACK)
# 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