Bird
0
0

Identify the error in this Ruby code that tries to add an item to an array:

medium📝 Debug Q14 of 15
Ruby - Arrays
Identify the error in this Ruby code that tries to add an item to an array:
numbers = [1, 2, 3]
numbers.add(4)
AThe syntax for array creation is wrong
BThe array is immutable and cannot be changed
CThe method 'add' does not exist for arrays
DThe number 4 must be inside quotes
Step-by-Step Solution
Solution:
  1. Step 1: Check the method used to add items to arrays

    Ruby arrays use 'push' or '<<' to add items, not 'add'.
  2. Step 2: Identify the error cause

    Calling 'add' on an array causes a NoMethodError because it is not a valid method.
  3. Final Answer:

    The method 'add' does not exist for arrays -> Option C
  4. Quick Check:

    Use 'push' or '<<' to add items [OK]
Quick Trick: Use 'push' or '<<' to add items to arrays [OK]
Common Mistakes:
MISTAKES
  • Using 'add' instead of 'push' or '<<'
  • Thinking arrays cannot be changed
  • Adding numbers as strings unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes