From: Paul Brannan Date: 2002-06-03T22:49:33+09:00 Subject: Re: Does assert() exist? On Mon, Jun 03, 2002 at 08:10:59PM +0900, 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)) I sometimes do something like this: $initial_directory = Dir.getwd def caller_file_pathname(filename) File.expand_path(filename, $initial_directory) end def parse_caller(caller_str) file, lineno, method = caller_str.split(':') if method =~ /in `(.*)'/ then method = $1.intern() end return file, lineno.to_i(), method end def caller_line(level=0) dir = File.dirname(caller_file_pathname($0)) file, lineno, method = parse_caller(caller[level.succ]) File.open(File.expand_path(file, dir)) do |input| (lineno.to_i - 1).times { input.gets } return input.gets end end if DEBUG then def assert(x, msg=nil) if not x then failed_msg = msg.nil? \ ? caller_line().sub(/^\s*/, '').chomp \ : msg puts "Assertion failed: #{failed_msg}" end end else def assert(x, msg=nil) end end but usually using one of the test libraries (Test::Unit, Rubyunit, Lapidary) is sufficient; assert_equal prints a MUCH more useful message than the above code. Paul