0
0
Rubyprogramming~5 mins

Ternary operator in Ruby

Choose your learning style9 modes available
Introduction
The ternary operator helps you choose between two values quickly in one line, making your code shorter and easier to read.
When you want to assign a value based on a simple condition.
When you need a quick if-else decision inside another expression.
When you want to return one of two values without writing a full if-else block.
Syntax
Ruby
condition ? value_if_true : value_if_false
The condition is checked first; if true, the first value is used.
If the condition is false, the second value is used.
Examples
Returns "Adult" if age is 18 or more, otherwise "Child".
Ruby
age >= 18 ? "Adult" : "Child"
Returns "Pass" if score is greater than 50, else "Fail".
Ruby
score > 50 ? "Pass" : "Fail"
Suggests taking an umbrella if it is raining.
Ruby
is_raining ? "Take umbrella" : "No umbrella needed"
Sample Program
This program asks for your age and uses the ternary operator to print if you are an adult or a child.
Ruby
puts "Enter your age:"
age = gets.to_i
result = age >= 18 ? "You are an adult." : "You are a child."
puts result
OutputSuccess
Important Notes
Use ternary operator only for simple conditions to keep code readable.
Avoid complex expressions inside ternary operators to prevent confusion.
Summary
The ternary operator is a short way to write if-else in one line.
It uses the syntax: condition ? value_if_true : value_if_false.
It is great for simple decisions and makes code cleaner.