How to use Ruby’s English and/or operators without going nuts

Years ago I wrote about Ruby’s English and/or operators and why they are the way they are. I’ve never been completely happy with how I made my case in that article, and more recently I took another whack at it in a RubyTapas episode. However, until now that episode hasn’t been available to the general public. Today that changes; I’ve made the episode freely available and you can watch it right here.

I’m told that some people have actually used my old article to warn programmers away from using the English “and”/”or” entirely. This makes me sad, because as you can see in the video above these operators enable some uniquely elegant and expressive constructs. I love how “or” lets me put the happy-path first in an expression that might need to handle a missing value. And I love how “and” lets me chain value-returning expressions together in a way that will short circuit as soon as one of the expressions fails to return a value.

I think their reputation for being confusing stems from thinking of them as boolean logic operators at all. If you think about them that way, then you have to keep remembering how they differ from the symbolic operators “&&” and “||”. Whereas if you think of them as control flow operators only, in the same vein as “if” and “unless”, they are a lot more self-explanatory.

I’ve also heard a compelling case made for the use of “and”/”or” operators as boolean logic operators in the context of “Seattle-style” parenthesis-free code. But that’s a blog post for another day.

[boilerplate bypath=”rubytapas-sample”]

17 comments

  1. Wow, I thought I knew this issue, but you’ve added something new. Didn’t know and/or were equal; I’ve added that to my Ruby Gotchas slide on those (https://docs.google.com/presentation/d/1cqdp89_kolr4q1YAQaB-6i5GXip8MHyve8MvQ_1r6_s ). I’ve avoided using and/or even for control flow because I’m so used to the “old-sk00l” ways and find these Perlisms jarring (and too reminiscent of Perl, which I don’t like) — but you’ve convinced me to give it another shot sometime.

  2. Excellent! A great help after recently running in to some of the (seemingly) anomalous behaviour of ‘and’ and ‘or’.

    Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *