Bird
0
0

Which of the following is the correct way to use the ternary operator in Ruby to assign result based on score?

easy📝 Syntax Q3 of 15
Ruby - Control Flow
Which of the following is the correct way to use the ternary operator in Ruby to assign result based on score?
Aresult = if score > 50 then 'Pass' else 'Fail' end
Bresult = score > 50 ? 'Pass', 'Fail'
Cresult = score > 50 then 'Pass' else 'Fail'
Dresult = score > 50 ? 'Pass' : 'Fail'
Step-by-Step Solution
Solution:
  1. Step 1: Understand ternary syntax

    The ternary operator in Ruby follows the format: condition ? value_if_true : value_if_false.
  2. Step 2: Analyze options

    result = score > 50 ? 'Pass' : 'Fail' correctly uses ? and : to separate true and false values.
    result = score > 50 ? 'Pass', 'Fail' incorrectly uses a comma instead of a colon.
    result = score > 50 then 'Pass' else 'Fail' uses incorrect keywords not valid in ternary.
    result = if score > 50 then 'Pass' else 'Fail' end uses if-else syntax, not ternary.
  3. Final Answer:

    result = score > 50 ? 'Pass' : 'Fail' -> Option D
  4. Quick Check:

    Check for ? and : in the expression [OK]
Quick Trick: Ternary uses '?' and ':' for true and false [OK]
Common Mistakes:
  • Using comma instead of colon between values
  • Using if-else keywords inside ternary
  • Omitting the colon ':' separator

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes