Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Arrays

What will be the output of this Ruby code?

arr = [nil, nil, nil]
arr.compact!
puts arr.inspect
A[nil, nil, nil]
B[] and then nil
Cnil
D[]
Step-by-Step Solution
Solution:
  1. Step 1: Understand compact! behavior

    compact! removes all nil values in place and returns nil if no changes were made, otherwise returns the modified array.
  2. Step 2: Apply compact! to array of only nils

    Since all elements are nil, compact! removes them all, leaving an empty array [].
  3. Final Answer:

    [] -> Option D
  4. Quick Check:

    compact! removes nil in place = B [OK]
Quick Trick: compact! modifies array, returns nil if no change [OK]
Common Mistakes:
  • Expecting compact! to return nil here
  • Confusing compact and compact! return values
  • Thinking array remains unchanged

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes