Bird
0
0

What is the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Enumerable and Collection Processing
What is the output of this Ruby code?
numbers = [2, 3, 4]
result = numbers.inject(1) { |product, n| product * n }
puts result
AError
B9
C10
D24
Step-by-Step Solution
Solution:
  1. Step 1: Understand the initial value and operation

    The initial value is 1, and each element multiplies the accumulator: 1*2=2, 2*3=6, 6*4=24.
  2. Step 2: Calculate the final product

    The final result after all multiplications is 24.
  3. Final Answer:

    24 -> Option D
  4. Quick Check:

    2*3*4 = 24 [OK]
Quick Trick: Multiply with inject starts at 1 [OK]
Common Mistakes:
  • Adding instead of multiplying
  • Starting with 0 causing zero result
  • Confusing output with sum

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes