Challenge - 5 Problems
Ternary Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code using ternary operator?
Consider the following Ruby code snippet. What will it print?
Ruby
x = 5 puts x > 3 ? "Greater" : "Smaller"
Attempts:
2 left
💡 Hint
Check if x is greater than 3 and what the ternary operator returns.
✗ Incorrect
Since x is 5, which is greater than 3, the condition is true, so the first string "Greater" is printed.
❓ Predict Output
intermediate2:00remaining
What does this nested ternary operator print?
Analyze the output of this Ruby code with nested ternary operators.
Ruby
a = 10 b = 20 puts a > b ? "a is bigger" : a == b ? "equal" : "b is bigger"
Attempts:
2 left
💡 Hint
Check the first condition a > b, then the second condition a == b.
✗ Incorrect
Since 10 > 20 is false, it checks a == b which is also false, so it prints "b is bigger".
🔧 Debug
advanced2:00remaining
What error does this Ruby code raise?
Identify the error raised by this Ruby code snippet using ternary operator.
Ruby
num = 7 result = num > 5 ? "High" : "Low" puts result
Attempts:
2 left
💡 Hint
Check if the line break affects the ternary operator syntax.
✗ Incorrect
Ruby allows line breaks after the ? operator if the expression continues, so no error occurs and since num is 7 > 5, it prints High.
❓ Predict Output
advanced2:00remaining
What is the value of variable 'output' after running this code?
Determine the value stored in 'output' after this Ruby code executes.
Ruby
value = nil output = value ? "Exists" : "Nil or false" puts output
Attempts:
2 left
💡 Hint
Remember how Ruby treats nil in conditionals.
✗ Incorrect
In Ruby, false and nil are falsy. value is nil, which is falsy, so the ternary returns "Nil or false".
❓ Predict Output
expert2:00remaining
What is the output of this Ruby code with complex ternary and method call?
Analyze the output of this Ruby code snippet.
Ruby
def check(num) num.even? ? "Even" : num > 10 ? "Odd and big" : "Odd and small" end puts check(7)
Attempts:
2 left
💡 Hint
Check the method call and nested ternary logic carefully.
✗ Incorrect
7 is odd (not even), so first condition false, then checks if 7 > 10 (false), so returns "Odd and small".