Bird
0
0

Examine the Ruby code below:

medium📝 Debug Q7 of 15
Ruby - Arrays

Examine the Ruby code below:

arr = [5, nil, 8, nil, 10]
arr.compact
puts arr.inspect

Why does the output still include nil values?

ABecause <code>compact</code> only removes <code>nil</code> values if called with a bang (<code>compact!</code>).
BBecause <code>compact</code> returns a new array and does not modify <code>arr</code> in place.
CBecause <code>puts</code> does not display arrays correctly.
DBecause <code>arr</code> contains frozen elements that cannot be removed.
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 original array

    Since arr.compact is called without assignment, the original arr remains unchanged.
  3. Step 3: Analyze other options

    compact! modifies in place but is not used here.
    puts correctly displays arrays.
    Frozen elements are unrelated.
  4. Final Answer:

    Because compact returns a new array and does not modify arr in place. -> Option B
  5. Quick Check:

    Assign arr = arr.compact to remove nils from original [OK]
Quick Trick: compact returns new array; original unchanged unless reassigned [OK]
Common Mistakes:
  • Assuming compact modifies original array
  • Confusing compact with compact!
  • Blaming puts for output format

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes