Challenge - 5 Problems
Compact Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of using compact on an array with nils?
Consider the following Ruby code:
What will be printed?
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
Attempts:
2 left
💡 Hint
compact removes all nil values from the array.
✗ Incorrect
The compact method returns a new array without any nil elements. So all nils are removed, leaving only the numbers.
❓ Predict Output
intermediate2:00remaining
What does compact! return when no nils are present?
Look at this Ruby code:
What will be printed?
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
Attempts:
2 left
💡 Hint
compact! returns nil if no changes were made.
✗ Incorrect
The compact! method modifies the array in place and returns nil if no nil elements were removed.
🔧 Debug
advanced2:00remaining
Why does this code raise an error?
This Ruby code is intended to remove nils from a hash's values:
But it raises an error. Why?
h = {a: 1, b: nil, c: 3}
h.compactBut it raises an error. Why?
Ruby
h = {a: 1, b: nil, c: 3}
h.compactAttempts:
2 left
💡 Hint
Check if Hash class supports compact method in this Ruby version.
✗ Incorrect
In Ruby 2.4 and later, Hash#compact is available, but if the environment is older or the method is undefined, calling compact on a hash raises NoMethodError.
❓ Predict Output
advanced2: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.inspectRuby
arr = [nil, 2, nil, 4] result = arr.compact.map { |x| x * 3 } puts result.inspect
Attempts:
2 left
💡 Hint
compact removes nils before map multiplies each number by 3.
✗ Incorrect
compact removes nils, leaving [2,4]. Then map multiplies each by 3, resulting in [6,12].
🧠 Conceptual
expert2:00remaining
How many items remain after compact on nested arrays?
Given this Ruby code:
What number will be printed?
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
Attempts:
2 left
💡 Hint
compact removes only top-level nils, not inside nested arrays.
✗ Incorrect
compact removes the nil elements at the top level, so the array becomes [1, [2, nil], [nil, 3]]. This has 3 elements.