From: Carlos Date: 2001-09-24T20:23:48+09:00 Subject: [ruby-talk:21627] Re: Please translate this easy snip of C++ to Ruby > Dave Thomas wrote: > > > trace {"a+f"} > > Forgot about blocks going in, but... > > I figured that with 'eval' (and with some shenanigans to transport the > scope), we'd have a solution that requires quotes. > > The python fix throws a private exception inside the 'trace', catches it, > examines the stack dump, opens the file containing the calling code, reads > the line by number, locates the 'trace', and reads what's inside the > parens. No quotes required. > > In Ruby can we inspect the current call stack this easy? or maybe easier? Yes, I think easier. Based on what you said about how it is done in Python and on Dave's solution, here is a simple, poorly tested approach: --- def trace_(&b) file,line_nr=caller()[0].split(':') line_nr=line_nr.to_i linecnt=1 expr=nil File.open(file).each_line do |line| if linecnt==line_nr if line =~ /(^|\W)trace_\s*{\s*(.*?)\s*}/ expr = $2 end break end linecnt+=1 end if expr puts "#{expr}: #{eval(expr, b).inspect}" end end a = 1 b = 2 trace_ { a + b }; c='x' * b; trace_{ c*2 } trace_ { 1+1 } --- Only one trace_ per line, no multiline blocks, and other limitations that are going to appear if you use this :)