On 8/2/07, Kenneth McDonald <kenneth.m.mcdonald / sbcglobal.net> wrote:
> I'm not talking anything quite so complex as design by contract, just
> the difference between
>
> if  x != y
>     ...raise new exception...
> end
>
> vs.
>
> assert x == y
>
> (which, in Python, raises an AssertionError, actually). It's nice to
> have a really fast, identifiable way of saying in code, "this (possibly
> nonobvious) condition is expected to hold at this point," and is (for
> me) as much about documenting twiddly bits of code as it is about error
> checking. I was surprised Ruby doesn't offer this, and hoped there'd be
> a bit if syntax or semantics I'd missed that took its place. Not a big
> deal though.
>
> Thanks,
> Ken
>
> Gregory Brown wrote:
> > On 8/1/07, Kenneth McDonald <kenneth.m.mcdonald / sbcglobal.net> wrote:
> >
> >> If you saw an earlier version of this question, apologies...I haven't
> >> seen it, so assume I accidentally deleted it or it got lost or some such.
> >>
> >> In other languages, I'm accustomed to using "assert" as a sort of
> >> enforceable documentation. Is there an equivalent statement or idiom in
> >> Ruby? I find that simply raising exceptions isn't quite right;
> >> exceptions are normally used when one thinks something might be done
> >> about a problem, whereas asserts are used to check that something is the
> >> way it always should be. An 'assert' makes this point in the code. On a
> >> lazier note, an 'assert' also needs less typing :-).

# Though, i have to admit, i never had any need for this kind of
check, here it is:

class AssertionError < StandardError
end

def assert a, b
  raise AssertionError, "#{a.inspect} != #{b.inspect}" unless a == b
end

assert 1, 1
assert 1, 2