Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Methods
What will be the output of this Ruby code?
def sum_all(*numbers)
  numbers.sum
end

puts sum_all(1, 2, 3, 4)
A1234
BError: undefined method 'sum'
C10
Dnil
Step-by-Step Solution
Solution:
  1. Step 1: Understand the method behavior

    The method collects all arguments into an array called numbers and calls sum on it.
  2. Step 2: Calculate the sum of arguments

    Arguments are 1, 2, 3, and 4. Their sum is 10.
  3. Final Answer:

    10 -> Option C
  4. Quick Check:

    Array.sum adds all elements correctly [OK]
Quick Trick: Use numbers.sum to add all *args elements easily [OK]
Common Mistakes:
  • Thinking sum concatenates numbers as strings
  • Assuming sum method is undefined
  • Forgetting *args collects arguments as array

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes