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

12.01.2005
| 21147 views |
  • submit to reddit
        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

Snippets Manager replied on Wed, 2006/07/05 - 12:51pm

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 - 1: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.