Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to remove nil values from the array.
Ruby
array = [1, nil, 2, nil, 3] clean_array = array.[1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'flatten' which changes nested arrays instead of removing nils.
Using 'uniq' which removes duplicates but keeps nils.
Using 'sort' which orders elements but does not remove nils.
✗ Incorrect
The compact method removes all nil values from an array.
2fill in blank
mediumComplete the code to remove nil values from the hash values.
Ruby
hash = {a: 1, b: nil, c: 3, d: nil}
clean_hash = hash.select { |_, v| v [1] } Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '== nil' which keeps only nil values.
Using comparison operators that don't relate to nil.
✗ Incorrect
The block keeps pairs where the value is not nil, effectively removing nil values.
3fill in blank
hardFix the error in the code to remove nil values from the array.
Ruby
numbers = [5, nil, 7, nil, 9] numbers = numbers.[1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'compact!' without parentheses which can cause syntax errors.
Using non-existent methods like 'compacted' or 'remove_nil'.
✗ Incorrect
The method compact returns a new array without nils. compact! modifies in place but requires parentheses.
4fill in blank
hardComplete the code to create a hash with word lengths, excluding nil words.
Ruby
words = ["apple", nil, "pear", nil, "plum"] lengths = {word => 0: word.{BLANK_2}}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using colon ':' instead of '=>', which is invalid in this context.
Using 'length' instead of 'size' (both work but only one is correct here).
✗ Incorrect
The hash uses word => 0 syntax and size method to get word length.
5fill in blank
hardFill all three blanks to create a hash of uppercase words and their lengths, excluding nils.
Ruby
words = ["dog", nil, "cat", "bird"] result = { [1]: [2] for word in words if word [3] nil }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'len(word)' which is Python syntax, not Ruby.
Using '==' instead of '!=' to exclude nil values.
✗ Incorrect
The key is the uppercase word, the value is its length, and the condition excludes nils.