P
Paul Mckibbin
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
[email protected]
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.
Mac
http://pqmf.com
once using the . nomenclature and once with an index into a hash.
i.e. in one case I had
[email protected]
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.
Mac
http://pqmf.com