And/Or

Episode 125 · August 15, 2013

Ruby has both symbolic and English forms of the logical “and” and “or” operators. Which one to choose may seem like a matter of taste, but that assumption can get you into trouble.

Script

Ruby has two different forms of logical operators. It has the "symbolic" form, such as && and ||. And it has English-style operators and and or.

nil || 42                       # => 42
42 && 23                        # => 23

nil or 42                       # => 42
42 and 23                       # => 23

At first glance the English operators and the symbolic operators seem to synonyms for each other. As a result, we may be tempted to use the English versions in preference to the symbolic versions in the interests of readability.

However, it doesn't take long before we start seeing surprising differences in behavior between the two sets of operators. For instance, here's some code that assigns a user object's name to a user_name variable. It uses the && operator to ensure that the .name message is only sent if the user is non-nil. So long as the user exists, the variable winds up having the expected username value.

But if we replace the && with the English and operator, the user_name variable takes on the value of the entire User object instead.

user = Struct.new(:name).new("Avdi")
user_name = user && user.name
user_name                       # => "Avdi"
user_name = user and user.name
user_name                       # => #<struct name="Avdi">

This happens because the English and has much lower operator precedence than the &&. So While the && operator takes precedence over the assignment, when it is replaced with the English and the assignment happens first.

user = Struct.new(:name).new("Avdi")
name = (user && user.name)
name                            # => "Avdi"
(name = user) and user.name
name                            # => #<struct name="Avdi">

Even more surprisingly, differences show up even in the simplest of logical expressions. Here's an expression using only symbolic operators. When we change all of the operators to English versions, the result changes.

:x || :y && nil                 # => :x
:x or :y and nil                # => nil

The reason for this is that not only do the English operators have lower precedence than the symbolic ones, but they also have differing precedence in relation to each other. Specifically, while the symbolic && has higher precedence than ||, the English and and or operators have equal precedence, so they are evaluated left to right.

:x || (:y && nil)               # => :x
(:x or :y) and nil              # => nil

At this point you may be starting to feel like the English logical operators are a trap: they look attractive, but when we actually put them to use they have surprising, seemingly arbitrary semantics.

To understand why these operators are the way they are, we have to understand where they come from. The English versions of the logical operators are one of the many features Ruby inherits from Perl. And in Perl, these operators have a purpose that's distinct from the symbolic logical operators: they are used as control-flow operators.

For example, here's a line of idiomatic Perl code straight from the Perl documentation. It tries to change working directory. If the operation fails, it raises an error, using the die keyword. In this example the program isn't interested in the boolean result of the or operator. Rather, it is exploiting the short-circuiting behavior of or to only execute the code on the right if the code on the left returns a falsey value.

chdir '/usr/spool/news' or die "Can't cd to spool: $!n"

Here's some Ruby code which behaves similarly. It uses the unless statement modifier to raise an exception unless it is able to read a line of text from $stdin.

raise "Can't read from STDIN" unless line = $stdin.gets

Let's say we'd like to put the read first and the error handling after it, similar to the Perl code we saw a moment ago. In order to do so, we might try to use logical a logical OR operator like so. But when we try to run it, we get a syntax error. As a result of the operator precedence rules, Ruby gets confused by this code.

line = $stdin.gets || raise "Can't read from STDIN" # !> possibly useless use of a literal in void context
# ~> -:1: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
# ~> line = $stdin.gets || raise "Can't read from STDIN"
# ~>                              ^

I could diagram exactly why this parse failed, but it's not worth it because we can easily fix the problem by switching from symbolic || to English or.

line = $stdin.gets or raise "Can't read from STDIN"
# ~> -:1:in `<main>': Can't read from STDIN (RuntimeError)

Let's move on to the and operator. Here's some Ruby code which outputs a notification if an enable_notifications flag is true. Right now it's using an if statement modifier to control whether or not the notification is sent.

def notify(message)
  puts "*** #{message}"
end

enable_notifications = true

notify "Something happened!" if enable_notifications
# >> *** Something happened!

Let's say we wanted to switch to using a logical operator to make the decision. We switch things around to put the flag first and use symbolic && to only send the notification when the flag is true. But then we run into a problem.

def notify(message)
  puts "*** #{message}"
end

enable_notifications = true

enable_notifications && notify "Something happened!" # !> possibly useless use of a literal in void context
# ~> -:7: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
# ~> enable_notifications && notify "Something happened!"
# ~>                               ^

Once again, we get a syntax error, because the Ruby gets confused about how the && fits together with the call to notify without parentheses. We could change the code to introduce parentheses… or we could simply use the English and operator and have everything just work.

def notify(message)
  puts "*** #{message}"
end

enable_notifications = true

enable_notifications and notify "Something happened!"
# >> *** Something happened!

In these two examples we can begin to see the reasoning behind the low precedence of these operators, and how it can be advantageous when they are used for control flow. Although truth be told, I don't really like the way this new and code reads; I preferred the original version with an if modifier on the end of the line. Let's move on to another example where English logical and makes more sense.

Here's some code that parses chunked HTTP content, as a web server might deliver it when it is streaming out data on the fly. The chunked encoding is a simple format where each chunk of data is preceded by a line containing a number indicating the length of the next chunk.

This code is written defensively to end early if any of its expectations about the incoming data are not met. First it reads a header line, which should contain the size of the next chunk. If that succeeds, it uses that size information to read the next chunk. And if that succeeds, it appends the last read chunk to an accumulator string.

require 'stringio'
chunked_data = StringIO.new("7rnHello, rn6rnworld!rn0rn")
data = ""
until chunked_data.eof?
  if chunk_head = chunked_data.gets("rn")
    if chunk = chunked_data.read(chunk_head.to_i)
      data << chunk
    end
  end
end
data                            # => "Hello, world!"

We can see this code forming a "chain" of sorts: We have a series of operations to perform, but if any of them is unsuccessful we don't want to proceed any further. We might think to turn this into a visual chain by stringing the statements together with AND operators instead of nesting them in if statements. We try this using symbolic &&, but even with parentheses around all method arguments we run into trouble.

require 'stringio'
chunked_data = StringIO.new("7rnHello, rn6rnworld!rn0rn")
data = ""
until chunked_data.eof?
  chunk_head = chunked_data.gets("rn") &&
    chunk = chunked_data.read(chunk_head.to_i) &&
    data << chunk
end
data                            # => 
# ~> -:7:in `<main>': can't convert nil into String (TypeError)

You know what comes next: when we replace the symbolic && operator with English and, our problems go away. We've successfully built a chain of short-circuiting dependent operations

require 'stringio'
chunked_data = StringIO.new("7rnHello, rn6rnworld!rn0rn")
data = ""
until chunked_data.eof?
  chunk_head = chunked_data.gets("rn") and
    chunk = chunked_data.read(chunk_head.to_i) and
    data << chunk
end
data                            # => "Hello, world!"

So what can we learn from these examples? First, we've seen that the English logical operators behave in surprising ways when used in boolean calculations. Second, we've seen that those very surprising parsing rules make these operators better suited than their symbolic counterparts when used as control-flow operators.

My advice is to take a page from Perl, and use the English logical operators strictly as control-flow constructs rather than evaluating them for their return value. Much as it might seem like an aesthetic improvement to substitute the English versions for symbolic operators in logical expressions, they simply aren't as well suited for that role.

That's it for now. Happy hacking!

Appears in

Tags: , , ,

Responses

  1. What I enjoy most of all in RubyTapas is the depth to which Avdi dives into a topic. This And/or topic looks quite simple from a first glance: never use them. However in the episode some history has been brought, so we understand why they’re here. And also clear example provided when and/or better than their logical counterparts.
    To be fair, I just wanted to say thank you once again. Didn’t have enough time to write shorter message:)

  2. Honestly, this video was great, because the english version of “and/or” were never even discussed during my bootcamp months, so this is all brand new information to me! It was just assumed that we would use || and &&. So that’s fun 😁

  3. I didn’t know about english version of || and &&. I’m not sure really what I learned here hahaha
    Maybe to be aware of its existence if I find it someplace, and that its better to stick to what I know for booleans (|| and &&) and if/else and other flow controls.

  4. I’ve seen this syntax before, but only in books/tutorials. It’s always been presented as synonymous with the symbolic versions, so it was great to get a deeper dive into how different the two really are.

    I think it leaves me wondering if I’ll be able to develop the eye to recognize when these keywords should be used when I’m actually writing code.

    1. That’s a great point.

      I think the thing to keep in mind is that you can get away with ignoring the English versions entirely. For boolean operations the symbolic versions are always the right choice, and for flow control you can always just use if or unless. Return to and and or only if there’s an if or unless construct that just feels awkward to you and you’re looking for a way to restate it.

  5. Wow! This is good to know. The Rubocop gem for rails advocates for the logical operators (and will change all of the english ones if you, like me, are in the habit of running “rubocop -a”). This explains a bug or two wherein I was following some documentation to implement another gem, the documentation of which used “or,” and then rubocop -a switched it to “||.” You just saved me a lot of debugging. I am so excited!

  6. This lesson motivated me to read more about control flow operators and it also surprised me because I did not know about the English versions of and/or. I enjoyed the lesson because it encouraged me to dive deeper in to things I think I would maybe overlook, just like “and” and “or”. I think I’ve seen them both used before online but I think I just brushed it off because I assumed it was just like the symbolic && and ||, but now I know that I should challenge my assumptions and take some time to examine things more.

  7. After the lesson, it made be want to dive more into control flows. In my time working with Ruby, I also have come to favor using “statement unless boolean” or “statement if boolean” type layout with evaluating logic.

    Also it is kind of annoying to always be taken away from the lesson I’m working on when I click ” Continue the discussion the forums” at the bottem of the lesson page. Could this open in a new tab instead of using the tab in use? I feel like I am constantly having to reopen the course page.

  8. This lesson immediately validated my initial instinct to sign up for this course! I found this particularly interesting, especially looking at how you can use and rather than nested if statements. I now have an urgency to write a blog post about object precedence and scour an open-source project for control flow improvements.

    Overall, I’m looking forward to this topic. I find it hard sometimes to handle control flow as it relates to exceptions and errors. Sometimes I find it difficult to switch back to a philosophy of Ruby and OOP languages in general, which says to fail silently, compared to Erlang, which encourages you to fail often and loudly.

  9. This is a great explanation of how to use “and”/”or” for control flow! I’ll mention one small hiccup that I ran into when I started using these keywords. I tried writing a function similar to this:

    puts 'foo' and return false if arg == :bar

    But it was my surprise when the console output was there but the function result was wrong!

    Looking back, I realized that puts returns nil, so the and logic stopped there. I learned that I still have to be careful of the expected values for each part of the statement!

    1. That’s a great point! It’s easy to think of “and” in terms of English “do this, then this” when really it’s “do this, and if that worked, do this other thing”.

      What you’re looking for is something like C’s “sequential operator” (the comma). Some Ruby options include:

      begin puts 'foo'; return false end if arg == :bar
      
      (puts 'foo'; return false) if arg == :bar
      
      puts('foo').then{ return false } if arg == :bar
      
  10. This is really great because generally and / or has been (in the last while) frowned upon, and this gives a great case for it immediately for control flow (and NOT return values!)!