I have a a hash
foo = {'bar'=>'baz'}
I would like to call foo.bar #=> 'baz'
My motivation is rewriting an activerecord query into a raw sql query (using Model#find_by_sql). This returns a hash with the SELECT clause values as keys. However, my existing code relies on object.method dot notation. I'd like to do minimal code rewrite. Thanks.
Edit: it appears Lua has this feature:
point = { x = 10, y = 20 } -- Create new table
print(point["x"]) -- Prints 10
print(point.x) -- Has exactly the same meaning as line above
There are a few gems for this. There's my recent gem, hash_dot, and a few other gems with similar names I discovered as I released mine on RubyGems, including dot_hash.
HashDot allows dot notation syntax, while still addressing concerns about NoMethodErrors addressed by @avdi. It is faster, and more traversable than an object created with OpenStruct.
It also maintains expected behavior when non-methods are called.
Please feel free to submit improvements or bugs to HashDot.
What you're looking for is called OpenStruct. It's part of the standard library.
Rather than copy all the stuff out of the hash, you can just add some behaviour to Hash to do lookups.
If you add this defintion, you extend Hash to handle all unknown methods as hash lookups:
Bear in mind that this means that you won't ever see errors if you call the wrong method on hash - you'll just get whatever the corresponding hash lookup would return.
You can vastly reduce the debugging problems this can cause by only putting the method onto a specific hash - or as many hashes as you need:
The other observation is that when
method_missing
gets called by the system, it gives you aSymbol
argument. My code converted it into aString
. If your hash keys aren't strings this code will never return those values - if you key by symbols instead of strings, simply substituten
forn.to_s
above.A good solution:
Note: this implementation has only one known bug:
If you prefer symbol lookups rather than string lookups, then swap the two 'if' condition