The Ruby ternary operator syntax

Here's a quick example of some Ruby source code, showing how I used Ruby's ternary operator in a method that prints a CSV record for a class I defined:

def print_csv_record
  last_name.length==0 ? printf(",") : printf("\"%s\",", last_name)
  first_name.length==0 ? printf(",") : printf("\"%s\",", first_name)
  city.length==0 ? printf(",") : printf("\"%s\"", city)
  printf("\n")
end

As you can see from that method, each line uses the ternary operator to make the following decision:

  1. If the length of the given field equals 0, use the first printf statement.
  2. Otherwise, use the second printf statement.

It may not seem like much, but that's it. The cool thing is that it's much shorter than the equivalent if/then syntax, and it's still very easy to read.

If you'd like a little more information on the Ruby ternary operator, feel free to read on.

General syntax of the ternary operator

As you can gather from the previous example, the general syntax for Ruby's ternary operator looks like this:

test-expression ? if-true-expression : if-false-expression

In my previous example, my first test-expression looked like this:

last_name.length==0

and its if-true-expression looked like this:

printf(",")

and its if-false-expression looked like this:

printf("\"%s\",", last_name)

Hopefully demonstrating the general syntax of the ternary operator helped make my earlier code a little more understandable.

A second example

If you'd like one more example of the ternary operator, here's one that uses a numeric test comparison, followed by two possible puts statements, one that will be executed if the test evaluates to true, and another that will be executed if the test evaluates to false:

# set the speed
speed = 90

# somewhere later in the program ...
speed > 55 ? puts("I can't drive 55!") : puts("I'm a careful driver")

As you might guess, this segment of code will print:

I can't drive 55!

(Which also summarizes my driving habits.)

The ternary operator is cool. It can shorten your if/then statements, and still keeps your Ruby code readable.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.