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
end

> which works for me, but I was wondering if there is a better way to do
> this than calling self.keys.include? to determine if the key exists
> without triggering any unexpected side effects.

Kind regards

	robert