The ternary operator helps you choose between two values quickly in one line. It makes simple decisions easy to write and read.
0
0
Ternary operator usage in Ruby
Introduction
When you want to assign a value based on a quick yes/no question.
When you want to print one message if something is true, and another if it is false.
When you want to shorten an if-else statement that fits in one line.
When you want to make your code cleaner and easier to understand for simple choices.
Syntax
Ruby
condition ? value_if_true : value_if_false
The condition is a question that is either true or false.
If the condition is true, the code uses value_if_true. Otherwise, it uses value_if_false.
Examples
This checks if
age is 18 or more. If yes, it returns "Adult", else "Child".Ruby
age >= 18 ? "Adult" : "Child"
Returns "Pass" if
score is greater than 50, otherwise "Fail".Ruby
score > 50 ? "Pass" : "Fail"
Chooses what message to show based on whether it is raining.
Ruby
is_raining ? "Take umbrella" : "No umbrella needed"
Sample Program
This program asks for your age, then uses the ternary operator to decide if you are an adult or a child. It prints the result.
Ruby
puts "Enter your age:" age = gets.to_i status = age >= 18 ? "Adult" : "Child" puts "You are a(n) #{status}."
OutputSuccess
Important Notes
The ternary operator is best for simple decisions. For complex choices, use full if-else blocks.
Remember to keep the code readable. If the line gets too long, break it into multiple lines.
Summary
The ternary operator is a short way to choose between two values.
It uses the format: condition ? value_if_true : value_if_false.
Use it to make your code cleaner for simple yes/no decisions.