From: David Alan Black Date: 2002-04-12T06:07:44+09:00 Subject: Re: How to Make a Method Ineffective Efficiently? Hello -- On Fri, 12 Apr 2002, William Djaja Tjokroaminata wrote: > Hi, > > I am having a problem regarding coding efficiency (both for the execution > time and for the typing itself). Basically, I have a method that may or > may not print depending on a flag, such as > > .... > def print_info (*text) > if @debugging > .... > @file.write (text.join) > end > end > > Originally, I have put the flag in the calling class itself, but it made > me typing the flag in too many places: > > .... > print_info ("#{obj1} #{obj2} .... #{obj1000}") if @debugging #format A > > (because in reality the flag or condition may not be that > short). Therefore, just like in the first fragment of codes, I have put > the flag in the print_info method itself, so that I can simply write > > .... > print_info ("#{obj1} #{obj2} .... #{obj1000}") #format B > > and whether it actually prints or not is controlled by the flag in the > print_info, which I can control without having to type in too many places. > > However, now I have a problem with execution efficiency. With the last > format (format B), whether or not I actually print, the methods to_s of > obj1, ..., obj1000 are called. The methods to_s themselves may be very > complicated. In the first format (format A), the methods to_s are not > called at all if @debugging is equal to false. > > I don't want to type "if @debugging" everywhere (they clutter the codes), > but I also want to have efficient execution, which in this case is > equivalent to if @debugging is false, then the print_info method is > ineffective, not even the passed arguments. Is there any way I can > accomplish what I want easily? > > (My current solution is to use format B, and try to minimize the argument > overhead, by minimizing the number of arguments and doing processing > inside the print_info method below the "if @debugging" line as much as > possible.) I haven't even tried to run this, let alone test it.... but could you put the stuff in a block instead of an argument list? Something like: def print_info if @debugging @file.write(yield) end end # ... print_info { "#{obj1} #{obj2}" } David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav