Bird
0
0

Identify the error in this Ruby code snippet:

medium📝 Debug Q14 of 15
Ruby - Error Handling
Identify the error in this Ruby code snippet:
def divide(a, b)
  raise "Cannot divide by zero" if b = 0
  a / b
end

puts divide(10, 0)
ADivision operator is incorrect
BMissing parentheses in raise statement
CUsing assignment (=) instead of comparison (==) in the if condition
DMethod divide is not defined
Step-by-Step Solution
Solution:
  1. Step 1: Check the if condition syntax

    The condition uses b = 0 which assigns 0 to b instead of comparing it. This is a common mistake.
  2. Step 2: Understand the impact

    Because of assignment, b becomes 0, and since 0 is falsy in Ruby, the condition evaluates to false, so the raise is not triggered. The intended check is b == 0.
  3. Final Answer:

    Using assignment (=) instead of comparison (==) in the if condition -> Option C
  4. Quick Check:

    Use == for comparison, not = [OK]
Quick Trick: Use == to compare, not = which assigns [OK]
Common Mistakes:
  • Confusing = and ==
  • Thinking raise needs parentheses
  • Assuming divide method is missing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes