Bird
0
0

What is the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Arrays

What is the output of the following Ruby code?

arr = [nil, 5, nil, 10]
new_arr = arr.compact
puts new_arr.inspect
puts arr.inspect
A[5, 10] [nil, 5, nil, 10]
B[nil, 5, nil, 10] [5, 10]
C[5, 10] [5, 10]
D[nil, nil] [nil, 5, nil, 10]
Step-by-Step Solution
Solution:
  1. Step 1: Understand what compact returns

    compact returns a new array without nil values, so new_arr is [5, 10].
  2. Step 2: Check if original array changes

    The original array arr remains unchanged as [nil, 5, nil, 10].
  3. Final Answer:

    [5, 10] [nil, 5, nil, 10] -> Option A
  4. Quick Check:

    compact returns new array, original unchanged = A [OK]
Quick Trick: compact returns new array; original stays same [OK]
Common Mistakes:
MISTAKES
  • Assuming original array changes after compact
  • Confusing compact with compact! which modifies original
  • Misreading output order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes