Bird
0
0

Which of the following is the correct syntax to sum all elements in an array arr using inject?

easy📝 Syntax Q12 of 15
Ruby - Enumerable and Collection Processing
Which of the following is the correct syntax to sum all elements in an array arr using inject?
Aarr.inject { |sum, n| sum / n }
Barr.inject(0) { |sum, n| sum + n }
Carr.inject(1) { |sum, n| sum * n }
Darr.inject { |sum, n| sum - n }
Step-by-Step Solution
Solution:
  1. Step 1: Identify the correct initial value and operation

    To sum elements, start with 0 and add each element: inject(0) { |sum, n| sum + n }.
  2. Step 2: Check other options

    arr.inject { |sum, n| sum - n } subtracts, C multiplies starting at 1, A divides. Only D sums correctly.
  3. Final Answer:

    arr.inject(0) { |sum, n| sum + n } -> Option B
  4. Quick Check:

    Sum with inject = D [OK]
Quick Trick: Sum needs 0 start and + inside block [OK]
Common Mistakes:
  • Starting sum with 1 instead of 0
  • Using wrong operation like subtraction
  • Omitting initial value causing errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes