From: Claude Brisson Date: 2004-02-17T15:14:54+09:00 Subject: Re: Hash like JS Hash (code) (second time I try to post... I did not see my post appear on the newslist... I hope it is not redundant, otherwise please mail me the answer) How would you achieve the same accesses with rexml elements, to access subelements or attributes ? I guess it's possible, but I'm still a ruby newbie... CloD "Gavin Kistner" a �crit dans le message de news:8hvXb.37945$uV3.63269@attbi_s51... > Although I may never use it, I thought I'd share the following > experiment. I find mildly frustrating the need to type: > myHash['foo'] > to access a property of my hash, when for strings > myHash.foo > seems perfectly logical. (At least to me, coming from JavaScript.) > > So I wrote the following code, which catches any methods not available > for hash and treats them like keys. (Thanks to memmove on #ruby-lang for > the idea of allowing setters in addition to getters.) > > > > class Hash > def method_missing(meth,*args) > if /=$/=~(meth=meth.id2name) then > self[meth[0...-1]] = (args.length<2 ? args[0] : args) > else > self[meth] > end > end > end > > x = { 'name'=>'Gavin', 'age'=>31 } > x.weight = 171 > x.feet = ['left','right'] > puts x.name , x.weight , x.foo , x.inspect > > PRODUCES > > Gavin > 171 > nil > {"name"=>"Gavin", "weight"=>171, "feet"=>["left", "right"], "age"=>31}