“and” and “or” are like backwards statement modifiers

It occurred to me after reviewing all the feedback to my last post that despite making the connection to statement modifiers, I never directly contrasted the two. And that this might be an even simpler way of explaining the usefulness of and/or in Ruby. I’ve added the following examples to the original post, but in case you missed it:


You can think of and is as a reversed if statement modifier:

  next if widget = widgets.pop


  widget = widgets.pop and next

Because of the low precedence of and, no extra parentheses are needed here as they would be for &&.


Likewise, or is a reversed unless statement modifier:

  raise "Not ready!" unless ready_to_rock?


  ready_to_rock? or raise "Not ready!"


Which version to use – if/unless or and/or – depends on your taste and what reads well in a given case. But it’s nice to have the option.


This entry was posted in Uncategorized and tagged , . Bookmark the permalink.
  • MLeoDaalder

    Of course, the if/unless and and/or relation is obvious when you know a little bit of logic:
    (a and b) == ((not a) or b) and (a or b) == ((not a) and b)

    • Whoever

      Rubbish. For example, the statement “(A and B) = ((not A) or B)” is false when A is false and B is true. That is because the left-hand side if false, but the right-hand side is true.

      • MLeoDaalder

        Woops, moment of befuddlement.
        ((not A) or B) is equivalent implication.
        What I meant to be quoting were the DeMorgan rules.

        The connection make a lot more sense combined with if/unless.

        (!(a ^ b)) == ((!a) v (!b))

  • seydar

    Yup. I've been using this a bit in Amp (http://amp.carboni.ca). It's really rather handy. Whenever I use a trick like this, I try to explain it so that a newbie could use my code as a learning tool.