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 # EligibleIt's the same as writing:
status = if age >= 18
"Eligible"
else
"Not Eligible"
endUse 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 itemsChallenge
EasyRead an integer n from input. Using the ternary operator (no if/else blocks), print exactly:
<n> is <label>where label is:
positivewhenn > 0negativewhenn < 0zerowhenn == 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier