Bird
0
0

You want to sum all numbers in an array using an iterator instead of a loop. Which Ruby code correctly does this?

hard📝 Application Q8 of 15
Ruby - Loops and Iteration
You want to sum all numbers in an array using an iterator instead of a loop. Which Ruby code correctly does this?
Asum = arr.each { |n| n + n } puts sum
Bsum = 0 arr.each { |n| sum += n } puts sum
Csum = 0 for n in arr sum = n end puts sum
Dsum = 0 arr.each do |n| sum = n * 2 end puts sum
Step-by-Step Solution
Solution:
  1. Step 1: Understand summing with each

    Initialize sum to 0, then add each element to sum inside the block.
  2. Step 2: Check each option

    sum = 0 arr.each { |n| sum += n } puts sum correctly accumulates sum; others overwrite or misuse each.
  3. Final Answer:

    sum = 0 arr.each { |n| sum += n } puts sum -> Option B
  4. Quick Check:

    Sum with iterator = C [OK]
Quick Trick: Use sum += n inside each block to accumulate values [OK]
Common Mistakes:
  • Overwriting sum instead of adding
  • Misusing each return value
  • Using for loop syntax incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes