From: dale.quigg@... Date: 2006-12-05T05:20:08+09:00 Subject: Re: How to make "generic" YAML calls? Gregory Seidman wrote: > On Fri, Dec 01, 2006 at 08:45:05AM +0900, dale.quigg@aspentech.com wrote: > } dale.quigg@aspentech.com wrote: > } > } > However, I want to write a class where I pass something like > } > '["This"]["Thing"]' > } > or > } > '["That"]["Thing"]' > } > and then make a call like; > } > puts LocalTree@YamlLocation > } > but I can't figure out how to make this work. > } > } Found it, sorry to bother. > } yaml_vari = '["This"]["Thing"]' > } puts eval("LocalTree" + yaml_vari) > > In general, eval should be avoided. Try this: > > def retrieve(*path) > path.inject(LocalTree) { |obj,key| obj[key] } > end > > Call it as retrieve('This', 'Thing'), for your example. > > --Greg Thank you Greg. I applied your suggestion to my application and it works. In trying to further understand how .inject works, I looked in the pickaxe book and found that this would cause (possibly many) intermediate values to be retrieved (depending on YAML configuration) while only the last value is returned. I ran a quick benchmark and the .inject code was about 28% slower than using eval in my application. This "slowdown" doesn't really matter, but I was thinking that perhaps it could be significant if the YAML file size increased. But, if this happens, perhaps I shouldn't be using YAML to store the data. :-) Do you know of a way to reduce the number of evaluations that occur when using inject? Also, can you give a quick pointer as to why eval should be avoided? Thanks again for your reply. Dale