1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

The Ternary (or "Conditional") Operator


Businesswoman on computer at office workstation
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 kind of short-hand, compact if statement. It has its uses, but it's also a bit controversial.

First, an example.

#!/usr/bin/env ruby

print "Enter a number: "
i = gets.to_i

puts "Your number is " +
 (i > 10 ? "greater than" : "less than or equal to") +
 " 10"

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 block that gets executed. So, you could re-write the previous example like so.

#!/usr/bin/env ruby

print "Enter a number: "
i = gets.to_i

string = if i > 10
          "greater than"
          "less than or equal to"

puts "Your number is " + string + " 10"

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 otherwise, 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.

So what uses does the ternary operator have? It does have uses, but there aren't many. 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. You could get along fine without it, but it does have its uses. Here are two typical use cases you'll see for the ternary operator.

# Pass d or e?
method_call(a, b, a + b > c ? d : e)

# Assign c or d?
a = b > 10 ? c : d

You may have noticed that this looks quite un-Ruby. Complex expressions just don't belong on one line in Ruby, it's usually all split up and easier to read. But 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 anything more complex, you should probably be using an if statement instead.

  1. About.com
  2. Technology
  3. Ruby

©2014 About.com. All rights reserved.