What Are Ternary (Conditional) Operators in Ruby?

A aoman using a computer in an office.

Thomas Barwick/Stone/Getty Images

The ternary (or conditional) operator will evaluate an expression and return one value if it's true, and another value if it's false. It's a bit like a shorthand, compact if statement.

Ruby's ternary operator has its uses but it's also a bit controversial.

Ternary Operator Example

Let's look at this example:

Here, the conditional operator is being used to select between two strings. The entire operator expression is everything including the conditional, question mark, two strings, and the colon. The general format of this expression is as follows: conditional ? true : false.

If the conditional expression is true, then the operator will evaluate as the true expression. Otherwise, it will evaluate as the false expression. In this example, it's in parentheses, so it doesn't interfere with the string concatenation operators surrounding it.

To put this another way, the conditional operator is like an if statement. Remember that if statements in Ruby evaluate to the last value in the block that gets executed. So, you could rewrite the previous example like so:

This code is functionally equivalent, and perhaps a bit easier to understand. If i is greater than 10, the if statement itself will evaluate to the string "greater than" or will evaluate to the string "less than or equal to." This is the same thing that the ternary operator is doing, only the ternary operator is more compact.

Uses for the Ternary Operator

So, what uses does the ternary operator have? It does have uses, but there aren't many, and you could get along fine without it.

It's usually used to shoehorn in values where conditionals would be too bulky. It's also used in variable assignment to quickly select between two values. 

Here are two typical use cases you'll see for the ternary operator:

You may have noticed that this looks quite un-Ruby. Complex expressions just don't belong on one line in Ruby - it's usually split up and easier to read. However, you will see this operator, and it can be used effectively without getting out of hand.

One rule to follow is that if you're using this operator to select between two values with a simple conditional, it's OK to use. If you're doing something more complex, you should probably be using an if statement instead.

mla apa chicago
Your Citation
Morin, Michael. "What Are Ternary (Conditional) Operators in Ruby?" ThoughtCo, Apr. 5, 2023, thoughtco.com/ternary-or-conditional-operator-2907827. Morin, Michael. (2023, April 5). What Are Ternary (Conditional) Operators in Ruby? Retrieved from https://www.thoughtco.com/ternary-or-conditional-operator-2907827 Morin, Michael. "What Are Ternary (Conditional) Operators in Ruby?" ThoughtCo. https://www.thoughtco.com/ternary-or-conditional-operator-2907827 (accessed May 30, 2023).