DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Basic Ruby Assert Function

  • submit to reddit
        A very simple way to add assert capability to function.
def assert
  raise "Assertion failed !" unless yield if $DEBUG
Usage :
def aFunc(i)
  assert { i < 10 }
  # ...

$DEBUG = true
# Ok.
# Raise Assert Exception.

$DEBUG = false
# Ok.


Snippets Manager replied on Wed, 2006/07/05 - 11:51am

The function could print a message as below: def assert(*msg) raise "Assertion failed! #{msg}" unless yield if $DEBUG end

Jens Alfke replied on Sat, 2006/01/28 - 12:28am

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.