Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Basic ruby assert function (See related posts)

A very simple way to add assert capability to function.
def assert
  raise "Assertion failed !" unless yield if $DEBUG
end

Usage :
def aFunc(i)
  assert { i < 10 }
  # ...
end

$DEBUG = true
# Ok.
aFunc(5)
# Raise Assert Exception.
aFunc(15)

$DEBUG = false
# Ok.
aFunc(5)
aFunc(15)

Comments on this post

snej posts on Jan 28, 2006 at 00:35
Using a block for the test is a clever way to avoid evaluating the block unless the $DEBUG flag is set. I wouldn't have thought of that!

However, I'm wondering what the overhead is of having the block at all; that is, how much work has to be done to generate the context the caller passes to the method. Depending on the implementation, that might be considerably more than was saved, at least if the assertion test is something fast like "i<10". For an expensive test your approach would always be a win, though.
chicoary posts on Jul 05, 2006 at 13:08
The function could print a message as below:

def assert(*msg)
raise "Assertion failed! #{msg}" unless yield if $DEBUG
end

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts