Bird
0
0

Fix the error in this Ruby method so it returns the sum of two numbers:

medium📝 Debug Q7 of 15
Ruby - Methods
Fix the error in this Ruby method so it returns the sum of two numbers:
def add(a, b)
  a + b
  puts "Sum calculated"
end
ARemove puts or place it before the sum expression
BAdd explicit return before a + b
CChange puts to print
DMove puts before a + b
Step-by-Step Solution
Solution:
  1. Step 1: Understand method return with puts

    The last expression is puts "Sum calculated", which returns nil, so method returns nil.
  2. Step 2: Fix method to return sum

    To return sum, remove puts or place it before a + b so the last expression is sum.
  3. Final Answer:

    Remove puts or place it before the sum expression -> Option A
  4. Quick Check:

    Last expression determines return, puts returns nil [OK]
Quick Trick: Last expression return matters; puts returns nil [OK]
Common Mistakes:
  • Thinking puts returns the string printed
  • Adding return after puts without changing order
  • Changing puts to print without fixing return

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes