From: Kenneth McDonald Date: 2007-08-02T15:40:32+09:00 Subject: Re: Is there a standard "assert" idiom in Ruby? 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 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 :-). >> > > Because Ruby's objects (and thus, their methods) are always open for > modification, this kind of mechanism is less helpful in Ruby than it > might be in other languages. There are design by contract frameworks > out there that do what you're looking for, but this often strikes most > seasoned Rubyists as being an imported practice from other languages, > rather than something that's really needed in Ruby. > > I don't find exception raising to necessarily indicate that something > might be done about a problem, but it's not a bad thing that they can > easily be caught. Can you think of a reason why you wouldn't want a > user to possibly handle a failed assertion? > > I think that if you describe the kinds of problems you're trying to > solve with assert, folks here will be able to best recommend the > idiomatic approach to handling them. It's possible that the kind of > work you're doing really needs this kind of behaviour, and then you > would need to either find a suitable third party library or roll your > own code. However, it's a little more likely that you're seeking a > solution to a problem that doesn't really exist in Ruby. > > -greg > > >