Challenge - 5 Problems
Ternary Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate1:30remaining
Output of a simple ternary expression
What is the output of this Ruby code?
Ruby
result = 5 > 3 ? "yes" : "no" puts result
Attempts:
2 left
💡 Hint
The ternary operator chooses the first value if the condition is true.
✗ Incorrect
Since 5 is greater than 3, the condition is true, so the expression returns "yes".
❓ Predict Output
intermediate1:30remaining
Ternary operator with numeric result
What will be the output of this Ruby code?
Ruby
num = 10 result = num.even? ? num / 2 : num * 3 puts result
Attempts:
2 left
💡 Hint
Check if the number is even and then apply the correct operation.
✗ Incorrect
10 is even, so the expression returns 10 / 2 which is 5.
❓ Predict Output
advanced2:00remaining
Nested ternary operator output
What is the output of this Ruby code with nested ternary operators?
Ruby
score = 75 result = score > 90 ? "A" : score > 80 ? "B" : score > 70 ? "C" : "F" puts result
Attempts:
2 left
💡 Hint
Evaluate conditions from left to right carefully.
✗ Incorrect
75 is not greater than 90 or 80, but it is greater than 70, so the result is "C".
❓ Predict Output
advanced1:30remaining
Ternary operator with method call
What will this Ruby code output?
Ruby
def check(num) num > 0 ? "positive" : "non-positive" end puts check(-1)
Attempts:
2 left
💡 Hint
Check the condition num > 0 for -1.
✗ Incorrect
Since -1 is not greater than 0, the ternary returns "non-positive".
🧠 Conceptual
expert2:00remaining
Understanding ternary operator precedence
What is the value of variable x after running this Ruby code?
Ruby
x = false || true ? 1 : 2
Attempts:
2 left
💡 Hint
Remember that ternary operator has higher precedence than || operator.
✗ Incorrect
The expression is evaluated as false || (true ? 1 : 2). The ternary returns 1, so false || 1 is 1 (truthy), and in Ruby, || returns the first truthy value, which is 1, so x is 1.