From: Robert Dober Date: 2009-04-22T06:51:03+09:00 Subject: Re: Is there a better way to do this? On Tue, Apr 21, 2009 at 11:40 PM, Robert Klemme wrote: > On 21.04.2009 21:01, Paul Mckibbin wrote: >> >> I recently had code which needed to work with the same structure twice, >> once using the . nomenclature and once with an index into a hash. > > If I understand the rest of your post correctly it is not exactly the same > structure but rather similarly structured data in two different data > structures (custom classes and XML DOM). > > The fix that I propose is to not have two data structures storing the same > data.  If you have classes already for storing all this, I'd probably write > bit of code that builds the structure using an XML push or pull parser. > >> i.e. in one case I had >> >> entries=@log.entry >> >> which I would interrogate with: >> >> entries.timings.connect.first_byte >> >> or alternatively >> >> entries.XmlSimple(in_file) >> >> which I would interrogate with: >> >> entries['timings']['connect']['first_byte']. >> >> Rather than write two blocks for code, one for the in-memory, I decided >> to override the base structure that XmlSimple used, but I found out that >> it was Hash. So the following was what I came up with: >> >>  class Hash >>    def method_missing(sym,*args,&blk) >>     return self[sym] if self.keys.include?(sym) >>     return self[sym.to_s] if self.keys.include?(sym.to_s) >>     super >>    end >>  end > > Usually nil is returned for absent keys so you can do > > def method_missing(sym,*args,&blk) >  self[sym] || self[sym.to_s] || super the following line will work for all potential hash values fetch( sym ) { fetch( sym.to_s ) { super } } HTH Robert