Bird
0
0

How can you modify this method to explicitly return the sum?

hard📝 Application Q9 of 15
Ruby - Methods
How can you modify this method to explicitly return the sum?
def sum_numbers(nums)
  total = 0
  nums.each do |n|
    total += n
  end
  total
end
AAdd <code>return total</code> after the loop
BAdd <code>return total if total > 0</code> inside the loop
CAdd <code>return total</code> inside the loop
DAdd <code>return total unless total > 0</code> after the loop
Step-by-Step Solution
Solution:
  1. Step 1: Understand method's current behavior

    Currently, method sums all numbers and returns total implicitly.
  2. Step 2: Add explicit return after loop

    Adding return total after the loop explicitly returns the sum.
  3. Final Answer:

    Add return total after the loop -> Option A
  4. Quick Check:

    Explicit return after loop returns final sum [OK]
Quick Trick: Place return after loop to return final result explicitly [OK]
Common Mistakes:
MISTAKES
  • Returning inside loop prematurely
  • Using return with condition inside loop incorrectly
  • Returning before sum is complete

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes