Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the first match of the pattern in the string.
Ruby
result = 'hello123'.match([1])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string instead of a regular expression.
Forgetting to use slashes around the pattern.
✗ Incorrect
The match method expects a regular expression, so /\d+/ correctly matches digits.
2fill in blank
mediumComplete the code to get the matched substring from the MatchData object.
Ruby
match = 'abc123'.match(/\d+/) matched_text = match[1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 1 which returns the first capture group, not the full match.
Using .string which returns the original string, not the match.
✗ Incorrect
Accessing index 0 of MatchData returns the entire matched substring.
3fill in blank
hardFix the error in the code to safely check if a pattern matches the string.
Ruby
if 'test123'.match(/\d+/)[1] puts 'Match found' else puts 'No match' end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking '== true' which is incorrect because match returns MatchData or nil.
Checking '!= false' which is not reliable for nil checks.
✗ Incorrect
match returns nil if no match, so checking '!= nil' confirms a match.
4fill in blank
hardComplete the code to create a hash of words and their lengths for words longer than 3 characters.
Ruby
words = ['cat', 'house', 'dog', 'elephant'] lengths = {word=> len(word) for word in words if word[1] 3}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the condition.
Using '.to_sym =>' which is not needed here.
✗ Incorrect
The hash uses 'word => len(word)' and the condition checks if word.length > 3.
5fill in blank
hardFill all three blanks to extract named captures from a string using MatchData.
Ruby
text = 'Name: John, Age: 30' pattern = /Name: (?<name>\w+), Age: (?<age>\d+)/ match = text.match([1]) name = match[2][:name] age = match[3][:age]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using .named_captures which returns a hash, not accessed with [:name].
Using .captures which returns an array, not a hash.
✗ Incorrect
Use the pattern variable in match, then access named captures with match[:name] and match[:age].