Automatically creating . for Ruby Hashes

Posted by blackrat on April 21, 2009

I recently had to so some testing of an in-memory OLE object, which also allowed persistance to an XML file. The structure of the two (in-memory and in-file) were similar enough for me to look at XMLSimple, which creates a Hash, and since I only like writing code once where I figured that using the same code would be cool.

In memory I needed to do
entry.timing.connect

and with the file (via entry=XmlSimple(infile))
entry[:timing][:connect]

Those were similar enough for me to want to change how XmlSimple held its Hash internally, but I figured that there may be a more generic way to do this without breaking Hash. That led me to try out the following code

  class Hash
    def method_missing(sym,*args,&blk)
     return self[sym] if self.key?(sym)
     return self[sym.to_s] if self.key?(sym.to_s)
     super
    end
  end

which just appears to work. Enjoy.

Trackbacks

Use this link to trackback from your own site.

Comments

You must be logged in to leave a response.