featurizing debug()

Raility Checkers:

Everyone needs a little debug() now and then. The RHTML statement <%=
debug(x) %> will barf out the value of x into the output page, inside
a tasteful grey DIV.

Suppose x were a complex expression. Or suppose (quell horror!) we
have several debugs, and they come and go.

Suppose I wanted debug() to also report the expression. debug(x + 1)
would emit x + 1: 43.

How to do that in Ruby?

(I could do it trivially in >cough< C++...)

Well, you do it pretty much the way you would in >cough< C++:

irb(main):001:0> def debug(exp)
irb(main):002:1> puts "#{exp} : #{eval(exp)}"
irb(main):003:1> end
=> nil
irb(main):004:0> debug('3+2')
3+2 : 5
=> nil
irb(main):005:0>

Rember the C and C++ preprocessors only deal with strings, so when you use
#define you're just doing some string substitution wherever the macro
appears in your >cough< code. The actual expressions are not evaluated until
later (ok, ok, some preprocessors are smart enough to fold simple invariant
expressions).

Does the above implementation of debug work for you?

Phlip wrote:

s.ross wrote:

irb(main):001:0> def debug(exp)
irb(main):002:1> puts "#{exp} : #{eval(exp)}"
irb(main):003:1> end

irb(main):004:0> debug('3+2')
3+2 : 5

Does the above implementation of debug work for you?

Wouldn't the eval() miss the scope of the calling function?

(If you can keep a secret, I still haven't figure out how to pass
scope, continuances (?), and locals into eval()...)

You need to pass in a binding to introduce context into the eval.

A small bit of info can be found here:

http://www.ruby-doc.org/core/classes/Kernel.html#M005735

V/r
Anthony