From: Robert Klemme Date: 2006-04-12T22:05:46+09:00 Subject: Re: Style question: if !x vs. unless x 2006/4/11, David Brady : > Hi all, > > One of the coolest things for me about learning ruby is that it's the > first language I've learned in a decade where I actually had to learn a > new language. Once you know C/C++, you can pick up Java, PHP, perl, > Python, and even VB without really having to learn new grammar... you > just learn where the braces and dollar signs go. One of the joys of > ruby is that when I find myself using a klunky grammar construct, there > is often an elegant solution if I will just surrender my C++ thinking style. > > That paragraph could spark a thread of its own, but in this case, its > lead-up for a simpler question. Which do you find more readable: > > # this version > if !correct > handle_error > do_some_other_thing > end > > # or this version > unless correct > handle_error > do_some_other_thing > end > > When dealing with single-lines, I find the inverted construct to be MUCH > more readable: > > handle_error unless correct In fact I'd usually make the above a single liner by using exceptions: raise SomeError unless correct # continue normal processing alternative correct or raise SomeError # continue normal processing > but when I have to make a block, my C++ instincts really prefer the "if > !" version. I usually use "unless" if there is a single negated expression and use "if" otherwise. No distinction with regard to single line or block. > Hmm, I just discovered this syntax, and for small blocks, I prefer it > greatly: > > ( handle_error; do_some_other_thing ) unless correct I don't like that. Use the normal if ... then .. end - that looks better, to me at least. Kind regards robert -- Have a look: http://www.flickr.com/photos/fussel-foto/