0
0
Rubyprogramming~10 mins

Named captures 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 define a named capture group called 'year' in the regex.

Ruby
regex = /(?<[1]>\d{4})/  # Matches a 4-digit year
Drag options to blanks, or click blank then click option'
Adate
Byear
Cmonth
Dday
Attempts:
3 left
💡 Hint
Common Mistakes
Using unnamed capture groups without the ? syntax.
Using incorrect group names like 'date' or 'month' when the pattern matches a year.
2fill in blank
medium

Complete the code to access the named capture 'month' from the match data.

Ruby
match = /(?<month>\d{2})/.match('07')
month = match[:[1]]
Drag options to blanks, or click blank then click option'
Amonth
Bdate
Cyear
Dday
Attempts:
3 left
💡 Hint
Common Mistakes
Using string keys instead of symbols.
Using the wrong capture group name.
3fill in blank
hard

Fix the error in the code to correctly define and use a named capture 'day'.

Ruby
regex = /(?<[1]>\d{2})/
match = regex.match('15')
day = match[:day]
Drag options to blanks, or click blank then click option'
Amonth
Bdate
Cday
Dyear
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatch between capture group name and symbol used to access it.
Using an undefined capture group name.
4fill in blank
hard

Fill both blanks to create a regex with named captures 'year' and 'month' and access them.

Ruby
regex = /(?<[1]>\d{4})-(?<[2]>\d{2})/
match = regex.match('2023-06')
year = match[:year]
month = match[:month]
Drag options to blanks, or click blank then click option'
Ayear
Bday
Cmonth
Ddate
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong capture group names that don't match the symbols used later.
Mixing up the order of year and month.
5fill in blank
hard

Fill all three blanks to create a regex with named captures 'year', 'month', 'day' and access them.

Ruby
regex = /(?<[1]>\d{4})-(?<[2]>\d{2})-(?<[3]>\d{2})/
match = regex.match('2023-06-15')
year = match[:year]
month = match[:month]
day = match[:day]
Drag options to blanks, or click blank then click option'
Ayear
Bmonth
Cday
Ddate
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect or inconsistent capture group names.
Not matching the capture group names with the symbols used to access them.