From: Tom Link Date: 2007-08-02T18:10:06+09:00 Subject: Re: Is there a standard "assert" idiom in Ruby? > Then you can do: > >> assert {3==3} > => nil > >> assert("This test will fail") {false} > AssertionError: This test will fail > from (irb):24:in `assert' > from (irb):29 > >> assert { 3>=1 } > => nil If implemented this way, assert comes with a potential speed penalty. This is why such an assert feature usually implies a command line option to ignore assertions in production mode (eg in Eiffel). In ruby this can in theory be done by using the method_added hook or similar. The code could then look like this pre {|a, b| a > 0 && b > 0} post {|r| r > 0} def foo(a, b) a + b end When a flag isn't set, pre & post could simply be ignored. There are some libraries around that try to achieve this but IMHO they all have some shortcoming. (Please correct me if I'm wrong.) I think that a general way to define such wrappers had to be part of ruby core language in order to get this right. If ruby were lisp, you could define your own def_by_contract. But AFAIK blocks cannot take optional arguments, which makes this currently impossible (or not so useful). Regards, Thomas. -- Posted via http://www.ruby-forum.com/.