Bird
0
0

Identify the issue in this Ruby code snippet:

medium📝 Debug Q6 of 15
Ruby - Enumerable and Collection Processing
Identify the issue in this Ruby code snippet:
nums = [5, 10, 15]
result = nums.inject(0) { |total, n| total - n }
puts result
AUsing subtraction in inject leads to unexpected results
BThe initial value should not be zero
CThe block parameters are in the wrong order
Dinject cannot be used with subtraction
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the operation

    The inject method starts with 0 and subtracts each element in sequence: 0 - 5 = -5, then -5 - 10 = -15, then -15 - 15 = -30.
  2. Step 2: Understand the problem

    Subtraction is not associative, so using inject with subtraction can produce unintuitive results.
  3. Final Answer:

    Using subtraction in inject leads to unexpected results -> Option A
  4. Quick Check:

    Subtraction accumulates differently than addition [OK]
Quick Trick: Avoid non-associative operations with inject [OK]
Common Mistakes:
  • Assuming inject always sums or multiplies
  • Expecting subtraction to behave like addition
  • Misunderstanding the order of operations in inject

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes