From: matt@... (matt neuburg) Date: 2009-04-22T04:55:09+09:00 Subject: Re: Is there a better way to do this? 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. > 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 > > 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. I would have thought that key? is the basic form here. Also, just a thought, you might look at ostruct which plays off the very same impulse you're having (i.e. to talk to hash as if it were a struct with accessors). The code might give you some ideas... m. -- matt neuburg, phd = matt@tidbits.com, http://www.tidbits.com/matt/ Leopard - http://www.takecontrolbooks.com/leopard-customizing.html AppleScript - http://www.amazon.com/gp/product/0596102119 Read TidBITS! It's free and smart. http://www.tidbits.com