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”]