From: Stefano Crocco Date: 2010-11-25T21:24:04+09:00 Subject: Re: instance_eval vs attr_reader On Thursday 25 November 2010 21:07:13 Joe Pikachu wrote: > Hi, I'm new in forum; even newer in programming. > I would like to know what is faster (uses less memory) to retrieve data? > I use ruby 1.8 series. > > my_class.instance_eval(@var) or > my_class.var #using attr_reader > > My question is based on the fact one have to asign a symbol to use the > 'attr_reader' type thus creating 'memory leaks', while not in the > former. But I'm not sure. > > > Thank You. The former wouldn't work, because it would call instance_eval passing the value of the instance variable @val of whichever object is self at the moment (not of my_class). To make it work as you wanted, you'd need to use my_class.instance_eval('@var') that is, you should pass a string containing the text '@var' to instance eval. However, attr_reader (and attr_writer and attr_accessor) are created precisely for the task you describe, so you can safely assume they can do it well. instance_eval (like eval and class_eval) are usually kept as last resource, when there's no other way to do what you want. They're more generic and so, most likely, less efficient than any other more specific tool. I hope this helps Stefano