0
0
Rubyprogramming~10 mins

Match method and MatchData in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A'\d+'
B/\d+/
C/hello/
D'hello'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string instead of a regular expression.
Forgetting to use slashes around the pattern.
2fill in blank
medium

Complete 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'
A.string
B.to_s
C[1]
D[0]
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.
3fill in blank
hard

Fix 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'
A!= false
B== nil
C!= nil
D== true
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.
4fill in blank
hard

Complete 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'
A.to_sym =>
B.length >
C.length <
D=>
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the condition.
Using '.to_sym =>' which is not needed here.
5fill in blank
hard

Fill 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'
Apattern
B.named_captures
C.captures
D.[]
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.