Bird
0
0

Identify the bug in this Ruby code:

medium📝 Debug Q7 of 15
Ruby - Arrays

Identify the bug in this Ruby code:

a = [1, 2, 3]
b = [3, 4, 5]
result = a + b - a
puts result.inspect
AThe subtraction removes all elements of a, resulting in only b's unique elements
BThe + operator cannot be used with arrays
CThe code will raise a runtime error
DThe result will be empty array
Step-by-Step Solution
Solution:
  1. Step 1: Understand the operations order

    a + b concatenates arrays, then subtracting a removes all elements from a in the result.
  2. Step 2: Analyze final array

    After subtraction, only elements unique to b remain: [4, 5].
  3. Final Answer:

    Subtraction removes all elements of a, leaving b's unique elements -> Option A
  4. Quick Check:

    Array addition and subtraction combine and remove elements [OK]
Quick Trick: Addition concatenates, subtraction removes elements [OK]
Common Mistakes:
  • Expecting subtraction to remove b elements
  • Thinking + is invalid
  • Expecting runtime error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes