Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Enumerable and Collection Processing
What will be the output of this Ruby code?
values = [4, 6, 8]
result = values.inject(2) { |acc, num| acc + num }
puts result
A20
B18
C24
D16
Step-by-Step Solution
Solution:
  1. Step 1: Understand initial value

    The inject method starts with an initial accumulator value of 2.
  2. Step 2: Perform accumulation

    It adds each element of the array to the accumulator: 2 + 4 = 6, then 6 + 6 = 12, then 12 + 8 = 20.
  3. Final Answer:

    20 -> Option A
  4. Quick Check:

    Sum with initial 2: 2 + 4 + 6 + 8 = 20 [OK]
Quick Trick: Add elements starting from initial value [OK]
Common Mistakes:
  • Forgetting to include the initial value in the sum
  • Multiplying instead of adding
  • Starting accumulation from zero instead of 2

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes