Is it idiomatic Ruby to add an assert( ) method to Ruby's Kernel class?

Andrew Harmel-Law picture Andrew Harmel-Law · Sep 29, 2008 · Viewed 36.2k times · Source

I'm expanding my Ruby understanding by coding an equivalent of Kent Beck's xUnit in Ruby. Python (which Kent writes in) has an assert() method in the language which is used extensively. Ruby does not. I think it should be easy to add this but is Kernel the right place to put it?

BTW, I know of the existence of the various Unit frameworks in Ruby - this is an exercise to learn the Ruby idioms, rather than to "get something done".

Answer

Julik picture Julik · Aug 11, 2009

No it's not a best practice. The best analogy to assert() in Ruby is just raising

 raise "This is wrong" unless expr

and you can implement your own exceptions if you want to provide for more specific exception handling