Bird
0
0

What is the output of the following Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Arrays

What is the output of the following Ruby code?

arr = [nil, 1, nil, 2, 3]
new_arr = arr.compact
puts new_arr.inspect
A[1, 2, 3]
B[nil, 1, nil, 2, 3]
C[1, nil, 2, 3]
D[nil, nil]
Step-by-Step Solution
Solution:
  1. Step 1: Apply compact to the array

    The compact method removes all nil values from the array, so [nil, 1, nil, 2, 3] becomes [1, 2, 3].
  2. Step 2: Understand output of puts with inspect

    puts new_arr.inspect prints the array as a string showing all elements, so the output is [1, 2, 3].
  3. Final Answer:

    [1, 2, 3] -> Option A
  4. Quick Check:

    compact removes nil = B [OK]
Quick Trick: compact removes nil, inspect shows array content [OK]
Common Mistakes:
MISTAKES
  • Expecting original array unchanged
  • Confusing output with original array
  • Thinking compact removes zeros

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes