0
0
Rubyprogramming~20 mins

Compact for removing nil values in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Compact Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of using compact on an array with nils?
Consider the following Ruby code:
arr = [1, nil, 2, nil, 3]
result = arr.compact
puts result.inspect

What will be printed?
Ruby
arr = [1, nil, 2, nil, 3]
result = arr.compact
puts result.inspect
A[1, 2, 3]
B[1, nil, 2, nil, 3]
C[nil, nil]
DError: undefined method 'compact'
Attempts:
2 left
💡 Hint
compact removes all nil values from the array.
Predict Output
intermediate
2:00remaining
What does compact! return when no nils are present?
Look at this Ruby code:
arr = [4, 5, 6]
result = arr.compact!
puts result.inspect

What will be printed?
Ruby
arr = [4, 5, 6]
result = arr.compact!
puts result.inspect
A[]
B[4, 5, 6]
Cnil
DError: undefined method 'compact!'
Attempts:
2 left
💡 Hint
compact! returns nil if no changes were made.
🔧 Debug
advanced
2:00remaining
Why does this code raise an error?
This Ruby code is intended to remove nils from a hash's values:
h = {a: 1, b: nil, c: 3}
h.compact

But it raises an error. Why?
Ruby
h = {a: 1, b: nil, c: 3}
h.compact
Acompact removes keys with nil values automatically
BHash does not have a compact method in Ruby 3.12
Ccompact only works on arrays, not hashes
Dcompact requires a block for hashes
Attempts:
2 left
💡 Hint
Check if Hash class supports compact method in this Ruby version.
Predict Output
advanced
2:00remaining
What is the output of chaining compact with map?
What does this Ruby code print?
arr = [nil, 2, nil, 4]
result = arr.compact.map { |x| x * 3 }
puts result.inspect
Ruby
arr = [nil, 2, nil, 4]
result = arr.compact.map { |x| x * 3 }
puts result.inspect
A[6, 12]
B[nil, 6, nil, 12]
C[2, 4]
DError: undefined method 'map' for nil
Attempts:
2 left
💡 Hint
compact removes nils before map multiplies each number by 3.
🧠 Conceptual
expert
2:00remaining
How many items remain after compact on nested arrays?
Given this Ruby code:
arr = [1, nil, [2, nil], [nil, 3], nil]
result = arr.compact
puts result.size

What number will be printed?
Ruby
arr = [1, nil, [2, nil], [nil, 3], nil]
result = arr.compact
puts result.size
A2
B5
C4
D3
Attempts:
2 left
💡 Hint
compact removes only top-level nils, not inside nested arrays.