0
0
Rubyprogramming~5 mins

Compact for removing nil values in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the compact method do in Ruby?
It returns a new array with all nil values removed from the original array.
Click to reveal answer
beginner
How do you use compact on an array [1, nil, 2, nil, 3]?
You call [1, nil, 2, nil, 3].compact, which returns [1, 2, 3].
Click to reveal answer
intermediate
What is the difference between compact and compact!?
compact returns a new array without nil values, while compact! modifies the original array in place and returns nil if no changes were made.
Click to reveal answer
beginner
Can compact remove values other than nil?
No, compact only removes nil values. Other falsy values like false remain in the array.
Click to reveal answer
beginner
Why might you want to use compact in your Ruby code?
To clean up arrays by removing unwanted nil values, which can help avoid errors or simplify processing.
Click to reveal answer
What does [1, nil, 3].compact return?
A[3]
B[nil]
C[1, nil, 3]
D[1, 3]
What does compact! do differently than compact?
AModifies the original array in place
BReturns a new array without nils
CRemoves false values
DDoes nothing
If an array has no nil values, what does compact! return?
AThe original array
BA new array
Cnil
DAn error
Which values does compact remove?
AAll falsy values
BOnly nil values
COnly false values
Dnil and false values
How can compact help in Ruby programming?
ABy cleaning arrays from nils to avoid errors
BBy sorting arrays
CBy converting arrays to strings
DBy adding nil values
Explain how the compact method works in Ruby and when you might use it.
Think about cleaning up arrays by removing empty spots.
You got /4 concepts.
    Describe the difference between compact and compact! in Ruby.
    One changes the original array, the other does not.
    You got /3 concepts.