Menu
Coddy logo textTech

Ternary Operator

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 40 of 56.

The ternary operator is a one-line shortcut for an if/else that returns a value. The syntax is condition ? value_if_true : value_if_false.

age = 20
status = age >= 18 ? "Eligible" : "Not Eligible"
puts status   # Eligible

It's the same as writing:

status = if age >= 18
           "Eligible"
         else
           "Not Eligible"
         end

Use the ternary when both branches return short values. If either branch needs more than one expression, fall back to a real if/else: packing too much into a ternary makes it hard to read.

You can use it directly inside other expressions, including interpolation:

count = 1
puts "#{count} item#{count == 1 ? "" : "s"}"   # 1 item
count = 5
puts "#{count} item#{count == 1 ? "" : "s"}"   # 5 items
challenge icon

Challenge

Easy

Read an integer n from input. Using the ternary operator (no if/else blocks), print exactly:

<n> is <label>

where label is:

  • positive when n > 0
  • negative when n < 0
  • zero when n == 0

Hint: use a nested ternary, condition ? a : (other_condition ? b : c).

For input 5 the output is 5 is positive. For 0 it's 0 is zero.

Cheat sheet

The ternary operator is a one-line if/else shortcut: condition ? value_if_true : value_if_false

age = 20
status = age >= 18 ? "Eligible" : "Not Eligible"  # "Eligible"

Ternaries can be nested and used inside string interpolation:

count = 5
puts "#{count} item#{count == 1 ? "" : "s"}"  # 5 items

# Nested ternary
n = 3
label = n > 0 ? "positive" : (n < 0 ? "negative" : "zero")

Use ternary only for short, simple branches — prefer if/else when branches need multiple expressions.

Try it yourself

n = gets.to_i

# TODO: use a ternary expression to build the label, then puts
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow