Bird
0
0

What will this Ruby code print?

medium📝 Predict Output Q5 of 15
Ruby - Blocks, Procs, and Lambdas
What will this Ruby code print?
sum = 0
[1, 2, 3].each { |x| sum += x }
puts sum
A0
B6
C123
DError
Step-by-Step Solution
Solution:
  1. Step 1: Understand each with block

    The each method iterates over each element, running the block for side effects but returns the original array.
  2. Step 2: Calculate the sum

    The block adds each element to sum, so sum becomes 1 + 2 + 3 = 6.
  3. Final Answer:

    6 -> Option B
  4. Quick Check:

    each with side effect updates sum = A [OK]
Quick Trick: each is for side effects, map returns new array [OK]
Common Mistakes:
  • Expecting each to return sum
  • Confusing sum with string concatenation
  • Thinking sum remains zero

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes