From: Kent Dahl Date: 2002-06-03T20:51:07+09:00 Subject: Re: Does assert() exist? Damon wrote: > This is very nice, but I wonder if Ruby can simulate a stringizing > assert macro from C, which I find more elegant: > > #define assert(x)(x || fprintf(stderr, "Assertion failed: %s\n", #x)) > > Thus, in C, the assertion > > assert(x != 1); > > if violated would print out > > Assertion failed: x != 1 > > The assertion expression gets evaluated, as well as converted into a > string for printing to standard error. Is it possible to do this in > Ruby? You could probably to some evil eval tricks, but I'm not sure how you would get the binding of the caller in an elegant way. This is ugly and slow, but atleast it is a startingpoint: def assert( &block ) code = block.call test = eval code, block print "Assertion '#{code}' " print (if test then 'ok' else 'failed' end) puts "." end x = 9 assert {'5==2+3'} #=> Assertion '5==2+3' ok. assert {'x==3*3'} #=> Assertion 'x==3*3' ok. assert {'x == 1'} #=> Assertion 'x == 1' failed. Only one I could think of where I didn't pass in the binding explicitly :-) -- (\[ Kent Dahl ]/)_ _~_ __[ http://www.stud.ntnu.no/~kentda/ ]___/~ ))\_student_/(( \__d L b__/ NTNU - graduate engineering - 4. year ) ( \__\_�|�_/__/ ) _)Industrial economics and technological management( \____/_�_\____/ (____engineering.discipline_=_Computer::Technology___)