Bird
0
0

Find the error in this Ruby code snippet:

medium📝 Debug Q6 of 15
Ruby - Arrays

Find the error in this Ruby code snippet:

arr = [1, nil, 2]
new_arr = arr.compact!
puts new_arr
ANo error; code works correctly
Bcompact! returns nil if no changes, so puts may print nothing
Ccompact! is not a valid method
Darr.compact! modifies arr but does not return new_arr
Step-by-Step Solution
Solution:
  1. Step 1: Understand compact! return value

    compact! returns nil if no nil values were removed, otherwise returns the modified array.
  2. Step 2: Check if any nils removed

    Since arr contains one nil, compact! removes it and returns the modified array, so new_arr is the array without nil.
  3. Step 3: Consider edge case

    If arr had no nils, compact! would return nil, and puts new_arr would print nothing, which can be confusing.
  4. Final Answer:

    compact! returns nil if no changes, so puts may print nothing -> Option B
  5. Quick Check:

    compact! may return nil = B [OK]
Quick Trick: compact! returns nil if no nil removed [OK]
Common Mistakes:
  • Expecting compact! always returns array
  • Thinking compact! is invalid
  • Ignoring nil return causing no output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes