Bird
0
0

You have an array data = [nil, 0, false, '', nil, 5]. You want to remove only nil values but keep 0, false, and empty strings. Which code correctly does this?

hard📝 Application Q15 of 15
Ruby - Arrays

You have an array data = [nil, 0, false, '', nil, 5]. You want to remove only nil values but keep 0, false, and empty strings. Which code correctly does this?

Aclean_data = data.reject!(&:nil?)
Bclean_data = data.compact
Cclean_data = data.select { |v| v }
Dclean_data = data.delete_if { |v| v.nil? }
Step-by-Step Solution
Solution:
  1. Step 1: Understand what compact does

    compact removes only nil values and keeps all other values including 0, false, and empty strings.
  2. Step 2: Analyze other options

    select { |v| v } removes all falsy values (nil, false, 0 is truthy in Ruby but empty string is truthy), so it removes false. reject!(&:nil?) modifies the original array. delete_if { |v| v.nil? } modifies original array.
  3. Step 3: Choose best option for new array without nil

    compact is simplest and returns new array without modifying original.
  4. Final Answer:

    clean_data = data.compact -> Option B
  5. Quick Check:

    compact removes nil only, keeps false and empty string = C [OK]
Quick Trick: Use compact to remove nil only, keep false and empty strings [OK]
Common Mistakes:
  • Using select which removes false values
  • Using delete_if which modifies original array
  • Using reject! which modifies the original array

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes