Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

What is the most readable way to write this in Ruby?

if (not url.blank?) and (not url.include?('*'))
share|improve this question

2 Answers 2

up vote 4 down vote accepted

Notes:

  • and/or are intended for flow control (statements involved), use &&/|| for boolean logic (pure expressions).
  • ! is more idiomatic than not
  • Avoid writing unnecessary parentheses.
  • Use possitive logic whenever possible: !x.blank? is equivalent to x.present?.

I'd write:

if url.present? && !url.include?('*')
share|improve this answer
    
I'm confused by your first item, because this is boolean logic, but it's for the purpose of flow control. Could you elaborate on the distinction? In particular, when should one use and/or? –  Vincent Jan 11 '13 at 3:55
    
@Vincent: Boolean logic d = (a && b) || !c. Flow control: x.empty? and return or args.present? or exit(1). More on this: devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby –  tokland Jan 11 '13 at 8:35
    
Reads much better than the original version. –  Pete Jan 11 '13 at 9:03
    
Thanks for the extra explanation @tokland, I feel I learned something ;-) –  Vincent Jan 13 '13 at 6:49

By boolean algebra theorems (specifically De Morgan's Laws) you could recode it as the following, which looks slightly more readable:

if not ( url.blank? or url.include?('*') )
share|improve this answer
2  
Applying boolean algebra is great and necessary, but as a side node: when writing app logic there is an important think to keep in mind, write it in the more declarative way for you (even if this could be simplified). –  tokland Jan 10 '13 at 9:01
    
if not ( ... ) could also be substituted for unless ... or if !( ... ) –  Nat Jan 10 '13 at 23:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.