B. Because compact does not remove nil values at all.
C. Because compact returns a new array but does not modify arr.
D. Because puts cannot print arrays correctly.
Solution
Step 1: Understand compact behavior
compact returns a new array without nil values but does not change the original array.
Step 2: Check why arr still has nil
Since arr.compact was called without assignment, arr remains unchanged and still contains nil.
Final Answer:
Because compact returns a new array but does not modify arr. -> Option C
Quick Check:
compact returns new array, original unchanged = D [OK]
Hint: Use compact! or assign compact result to change original [OK]
Common Mistakes:
Thinking compact modifies original array
Believing puts cannot print arrays properly
Assuming arr was reassigned automatically
5.
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
A. clean_data = data.reject!(&:nil?)
B. clean_data = data.compact
C. clean_data = data.select { |v| v }
D. clean_data = data.delete_if { |v| v.nil? }
Solution
Step 1: Understand what compact does
compact removes only nil values and keeps all other values including 0, false, and empty strings.
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.
Step 3: Choose best option for new array without nil
compact is simplest and returns new array without modifying original.
Final Answer:
clean_data = data.compact -> Option B
Quick Check:
compact removes nil only, keeps false and empty string = C [OK]
Hint: 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
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.