Bird
0
0

Which Ruby code snippet correctly creates a new array from arr without any nil values?

easy📝 Syntax Q3 of 15
Ruby - Arrays

Which Ruby code snippet correctly creates a new array from arr without any nil values?

arr = [4, nil, 7, nil, 9]
Anew_arr = arr.compact
Bnew_arr = arr.compact!
Cnew_arr = arr.delete(nil)
Dnew_arr = arr.reject(&:nil!)
Step-by-Step Solution
Solution:
  1. Step 1: Identify method that returns new array

    compact returns a new array without nil values, leaving original unchanged.
  2. Step 2: Understand difference with compact!

    compact! modifies the original array in place and returns nil if no changes were made.
  3. Step 3: Analyze other options

    arr.delete(nil) removes nil from original array and returns last deleted element, not a new array.
    reject(&:nil!) is invalid syntax.
  4. Final Answer:

    new_arr = arr.compact -> Option A
  5. Quick Check:

    Check if original array remains unchanged and new array excludes nil [OK]
Quick Trick: Use compact to get new array without nils [OK]
Common Mistakes:
  • Using compact! expecting a new array
  • Using delete which returns deleted element
  • Incorrect syntax with reject(&:nil!)

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes