From: Joel VanderWerf Date: 2007-09-16T08:42:50+09:00 Subject: Re: one line to print the statement AS WELL AS the evaluated value like in C Summercool wrote: > > On Sep 15, 10:49 am, Joel VanderWerf wrote: >> kendear wrote: >>> i wonder in Ruby, is there a line method to do something like in C >> def dbg(&bl) >> s = yield >> puts "#{s} = #{eval(s, bl).inspect}" >> end >> >> array=[0,1,2,3] >> dbg{"array[3]+1"} # ==> array[3]+1 = 4 >> >> It seems a little awkward to use both {...} and "..." around the >> expression, but the {} allows the #dbg method to capture the binding of >> the caller. > > It works! both for globals and for instance variables... > but what is this call dbg{"n"} using { } instead of ( ) > does it have a name? and does any book talk about it? The {..} is just ruby's block notation, just as in "each {...}" > i guess there is no way to do > > dbg(array[3] + 1) or dbg{array[3] + 1} without quoting it as > string huh? C was able to do it due to the preprocessor. Not easy. Another advantage of using the block notation is that you can disable evaluation with a global flag: def dbg if $debug s = yield puts "#{s} = #{eval(s, Proc.new).inspect}" end end If the flag is set, the dbg call is just a method call and a variable test. It doesn't even instantiate a Proc (note that I removed the &bl and added Proc.new). -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407