Bird
0
0

What will this Ruby code print?

medium📝 Predict Output Q5 of 15
Ruby - Loops and Iteration
What will this Ruby code print?
sum = 0
5.downto(3) { |i| sum += i }
puts sum
A12
B15
C8
D10
Step-by-Step Solution
Solution:
  1. Step 1: Identify the numbers in the downto loop

    The loop counts down from 5 to 3: 5, 4, 3.
  2. Step 2: Sum the numbers

    Sum = 5 + 4 + 3 = 12.
  3. Final Answer:

    12 -> Option A
  4. Quick Check:

    Sum of 5 to 3 = 12 [OK]
Quick Trick: Sum numbers inside downto block to accumulate [OK]
Common Mistakes:
MISTAKES
  • Adding numbers incorrectly
  • Confusing upto with downto
  • Off-by-one errors in range

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes