Recall & Review
beginner
What is the ternary operator in Ruby?
The ternary operator is a short way to write an if-else statement. It uses the syntax:
condition ? true_value : false_value.Click to reveal answer
beginner
How does the ternary operator work in Ruby?
It checks the condition before the
?. If true, it returns the value after ? and before :. If false, it returns the value after :.Click to reveal answer
beginner
Rewrite this if-else using a ternary operator:<br>
if age >= 18 status = 'adult' else status = 'minor' end
status = age >= 18 ? 'adult' : 'minor'
Click to reveal answer
intermediate
Can the ternary operator be nested in Ruby?
Yes, you can nest ternary operators, but it can make code hard to read. It's better to use if-else for complex conditions.
Click to reveal answer
beginner
What is a common use case for the ternary operator?
It is used for simple decisions to assign a value quickly without writing multiple lines of if-else statements.
Click to reveal answer
What does this Ruby code return?<br>
5 > 3 ? 'yes' : 'no'
✗ Incorrect
Since 5 is greater than 3, the condition is true, so it returns 'yes'.
Which symbol separates the true and false parts in a ternary operator?
✗ Incorrect
The colon ':' separates the true part (after '?') and the false part.
What is the output of this code?<br>
puts (10 == 10 ? 'Equal' : 'Not equal')
✗ Incorrect
10 == 10 is true, so it prints 'Equal'.
Is this a valid ternary operator usage in Ruby?<br>
result = condition ? do_something : do_something_else
✗ Incorrect
This is the correct syntax for a ternary operator.
Why might you avoid nesting ternary operators?
✗ Incorrect
Nesting ternary operators can make code confusing and hard to maintain.
Explain how the ternary operator works in Ruby and give a simple example.
Think of it as a short if-else in one line.
You got /6 concepts.
Describe a situation where using a ternary operator is better than an if-else statement.
When you want to assign a value quickly based on a condition.
You got /4 concepts.