Introduction To Ruby
The Ternary Operator

The ternary operator gets its name from the fact that it accepts 3 operands. Operators normally accept only 2. It provides a compact way to express conditionals.


# Ternary Fun

a = 5
b = 6

# if else version
puts "Traditional if"
if a==b then
  puts "a is equal to b"
  puts "a and b are not equal"


# with the ternary operator
puts "Ternary operator"
puts a==b ? "a is equal to b" : "a and b are not equal"


Some people find the ternary operator a little awkward to use. The best way to use it is when you are refactoring code. That means looking at a finished program and working out how to express it more compactly.