I tend to use assertions as a sort of runtime unit test, esp. when I'm 
in the rapid prototyping and design stage of a project. It find it 
easier to simply use them like a form of passive logging -- with enough 
'sanity-check' assertions in place, I can get a reasonably good 
post-mortem on where my code breaks, without having to run everything 
through the debugger or build dozens of test cases in advance (the 
former being an especially big win when I'm working with a distributed 
application that runs on multiple machines simultaneously).

I do tend to use blocks, rather than simple conditionals, in my 
assertion checking, simply so that when they're disabled, none of the 
work (or side-effects) from the block has to be done. By simply passing 
a boolean-valued parameter, (such as 'my_list.size > num_new_entries', 
or something) you force evaluation of it each time the assertion is 
encountered. If you use blocks, though, you can only call the block when 
assertions are turned on.

Since I like having the ability to enable or disable assertions at 
runtime, the block then adds no extra execution time (since it never 
gets called), and any side effects that could happen within it are 
avoided in cases where the assertion is disabled.

My simplistic implementation looks something like the following:

def assert(&block)
    if ASSERTIONS_ACTIVE
        begin
            block.call() or raise Exception, "assertion failed"
        rescue Exception => e
            [...similar backtrace handling...]
        end
    end
end

Lennon

Jason M Jurkowski ;002;icsg6; wrote:

> [snip]
>
>sometimes assertions don't check adherence to an interface.  sometimes you
>like to add assertions to help you determine where a program went wrong.
>you find which part of your understanding "broke first."
>
>i've coded up a ruby "assertion" for myself as follows:
>
>def assert(conditional)
>  begin
>    raise Exception, "assertion failed" if not conditional
>  rescue Exception => e
>    filename = e.backtrace()[1].split(/:/)[0]
>    lineno = e.backtrace()[1].split(/:/)[1].to_i()
>    file = File::new(filename)
>    puts e.message+": "+file.readlines()[lineno-1]
>    exit! 1
>  end
>end
>
>maybe as i learn more ruby i'll find less of a use for it.
>  
>
>>>jason
>>>      
>>>
>>--
>>Ryan Pavlik <rpav / users.sf.net>
>>
>>"Fanged death from the sea is quite routine." - 8BT
>>    
>>