Superhash: Easier Access to Ruby Hashes
by James
The short version
Ever wanted to do this?
Well now you can.
The long version
Recently, I’ve been working a Ruby project for which I wanted .method style access to hash values. This was for a DSL; in my opinion, it’s sometimes better to be able to do this…
…than this:
The first looks nicer, don’t you think? Sometimes looks are important. You run the risk of confusing users (the boundaries between “real” methods and hash value accessors are blurred), but in this case users will have a very clear idea of how their hashes work, so it’s not a big problem.
So, I wrote a little gem which does the job. And it is tiny! The gem is called Superhash and it’s available on Github. Basically, what Superhash does is intercept Ruby’s method_missing and look for hash keys corresponding to the method used:
This isn’t rocket science. But sometimes it’s fun to write something simple to scratch your own itch :)
To use, just require 'superhash' and you’re good to go. No includes needed. Check out the repository on Github, and let me know if you find it useful!