Bird
0
0

How would you rewrite this nested if-else using a ternary operator?

hard📝 Application Q9 of 15
Ruby - Operators and Expressions
How would you rewrite this nested if-else using a ternary operator?
if temp > 30
  status = "Hot"
elsif temp > 20
  status = "Warm"
else
  status = "Cold"
end
Astatus = temp > 30 ? "Hot" : temp > 20 "Warm" : "Cold"
Bstatus = temp > 30 ? "Hot" : "Warm" : "Cold"
Cstatus = temp > 30 ? "Hot" : temp > 20 ? "Cold" : "Warm"
Dstatus = temp > 30 ? "Hot" : temp > 20 ? "Warm" : "Cold"
Step-by-Step Solution
Solution:
  1. Step 1: Translate nested if-else to nested ternary

    The first condition checks temp > 30 for "Hot". If false, check temp > 20 for "Warm", else "Cold".
  2. Step 2: Verify correct ternary syntax and order

    status = temp > 30 ? "Hot" : temp > 20 ? "Warm" : "Cold" correctly nests ternary operators with proper '?' and ':' placement matching the if-elsif-else logic.
  3. Final Answer:

    status = temp > 30 ? "Hot" : temp > 20 ? "Warm" : "Cold" -> Option D
  4. Quick Check:

    Nested ternary matches nested if-else logic [OK]
Quick Trick: Nest ternaries carefully with correct punctuation [OK]
Common Mistakes:
  • Misplacing colons
  • Swapping true/false branches
  • Missing '?' in nested ternary

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes