Bird
0
0

Consider this Ruby code snippet:

medium📝 Debug Q14 of 15
Ruby - Arrays

Consider this Ruby code snippet:

arr = [1, nil, 2, nil, 3]
arr.compact
puts arr.inspect

Why does the output still include nil values?

ABecause <code>arr</code> was reassigned incorrectly.
BBecause <code>compact</code> does not remove <code>nil</code> values at all.
CBecause <code>compact</code> returns a new array but does not modify <code>arr</code>.
DBecause <code>puts</code> cannot print arrays correctly.
Step-by-Step Solution
Solution:
  1. Step 1: Understand compact behavior

    compact returns a new array without nil values but does not change the original array.
  2. Step 2: Check why arr still has nil

    Since arr.compact was called without assignment, arr remains unchanged and still contains nil.
  3. Final Answer:

    Because compact returns a new array but does not modify arr. -> Option C
  4. Quick Check:

    compact returns new array, original unchanged = D [OK]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes