Bird
0
0

Which of the following is the correct syntax to remove nil values from an array arr without changing arr itself?

easy📝 Syntax Q12 of 15
Ruby - Arrays

Which of the following is the correct syntax to remove nil values from an array arr without changing arr itself?

arr = [1, nil, 2, nil, 3]
Aarr.delete(nil)
Barr.compact!
Carr.remove_nil
Darr.compact
Step-by-Step Solution
Solution:
  1. Step 1: Identify method that returns new array without nil

    compact returns a new array without nil values and does not modify the original array.
  2. Step 2: Understand difference with compact!

    compact! modifies the original array, so it changes arr. delete(nil) removes nil but modifies arr. remove_nil is not a Ruby method.
  3. Final Answer:

    arr.compact -> Option D
  4. Quick Check:

    compact returns new array, compact! modifies [OK]
Quick Trick: Use compact for new array, compact! to modify original [OK]
Common Mistakes:
  • Using compact! when original array should stay unchanged
  • Using delete(nil) which modifies the original array
  • Assuming remove_nil is a valid Ruby method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes