Bird
0
0

Which of the following Ruby expressions correctly removes nil values from the array [1, nil, 2, nil, 3]?

easy📝 Conceptual Q2 of 15
Ruby - Arrays

Which of the following Ruby expressions correctly removes nil values from the array [1, nil, 2, nil, 3]?

A[1, nil, 2, nil, 3].filter(nil)
B[1, nil, 2, nil, 3].delete(nil)
C[1, nil, 2, nil, 3].compact
D[1, nil, 2, nil, 3].remove(nil)
Step-by-Step Solution
Solution:
  1. Step 1: Identify the method that removes nil values

    The compact method removes all nil values from an array and returns a new array without them.
  2. Step 2: Check other options for correctness

    delete(nil) removes all nils but modifies the original array and returns the last deleted element, not the array. remove and filter are not valid methods for this purpose.
  3. Final Answer:

    [1, nil, 2, nil, 3].compact -> Option C
  4. Quick Check:

    Use compact to remove nil values from arrays = D [OK]
Quick Trick: Use compact to get new array without nils [OK]
Common Mistakes:
  • Using delete returns wrong value
  • Using non-existent methods like remove
  • Expecting filter to remove nil without block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes