Bird
0
0

Why does inject without an initial value use the first element of the collection as the accumulator?

hard📝 Conceptual Q10 of 15
Ruby - Enumerable and Collection Processing
Why does inject without an initial value use the first element of the collection as the accumulator?
ATo optimize performance by avoiding block execution
BTo avoid requiring an explicit initial value and start accumulation naturally
CTo always skip the first element in the block
DBecause Ruby does not allow nil as initial value
Step-by-Step Solution
Solution:
  1. Step 1: Understand default behavior of inject

    If no initial value is given, inject uses first element as accumulator to start combining elements.
  2. Step 2: Reason why this is done

    This avoids forcing the user to provide an initial value and allows natural accumulation starting from first element.
  3. Final Answer:

    To avoid requiring an explicit initial value and start accumulation naturally -> Option B
  4. Quick Check:

    inject default initial = first element [OK]
Quick Trick: No initial value means first element is accumulator [OK]
Common Mistakes:
  • Thinking inject skips first element
  • Believing nil is default initial value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes