Bird
0
0

Identify the error in this Ruby method:

medium📝 Debug Q14 of 15
Ruby - Methods
Identify the error in this Ruby method:
def check_number(num)
  if num > 0
    return 'Positive'
  else
    'Negative'
  end
  return
end
AThe method has unreachable code after return.
BThe return keyword is used incorrectly inside if.
CThe else block should use return explicitly.
DThe method returns nil for negative numbers.
Step-by-Step Solution
Solution:
  1. Step 1: Trace the if branch

    If num > 0, return 'Positive' exits the method immediately.
  2. Step 2: Trace the else branch

    Else block evaluates 'Negative' as last expression (implicit return).
  3. Step 3: Check post-conditional code

    The final return (nil) is unreachable as if-else covers all paths.
  4. Final Answer:

    The method has unreachable code after return. -> Option A
  5. Quick Check:

    Complete if-else leads to unreachable code [OK]
Quick Trick: Check all paths return a value explicitly [OK]
Common Mistakes:
  • Assuming last return runs always
  • Thinking return inside if is wrong
  • Ignoring implicit returns

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes