Robert Dober
4/21/2009 9:51:00 PM
On Tue, Apr 21, 2009 at 11:40 PM, Robert Klemme
<shortcutter@googlemail.com> 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 sam=
e
> 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 sam=
e
> data. =A0If you have classes already for storing all this, I'd probably w=
rite
> bit of code that builds the structure using an XML push or pull parser.
>
>> i.e. in one case I had
>>
>> entries=3D@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:
>>
>> =A0class Hash
>> =A0 =A0def method_missing(sym,*args,&blk)
>> =A0 =A0 return self[sym] if self.keys.include?(sym)
>> =A0 =A0 return self[sym.to_s] if self.keys.include?(sym.to_s)
>> =A0 =A0 super
>> =A0 =A0end
>> =A0end
>
> Usually nil is returned for absent keys so you can do
>
> def method_missing(sym,*args,&blk)
> =A0self[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