0
0
Rubyprogramming~15 mins

Named captures in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Extracting Date Components with Named Captures in Ruby
📖 Scenario: Imagine you have a list of dates in the format YYYY-MM-DD. You want to pull out the year, month, and day parts separately to use them later, like sorting or filtering.
🎯 Goal: Build a Ruby program that uses a regular expression with named captures to extract the year, month, and day from a date string.
📋 What You'll Learn
Create a string variable called date with the value "2024-06-15".
Create a regular expression called date_regex that uses named captures for year, month, and day matching the date format.
Use the match method to match date against date_regex and store the result in a variable called match_data.
Print the extracted year, month, and day from match_data using the named captures.
💡 Why This Matters
🌍 Real World
Named captures help you pull out meaningful parts from text like dates, phone numbers, or codes, making it easier to work with data.
💼 Career
Many jobs require processing text data. Knowing how to use named captures in regex helps you write clear and maintainable code for data extraction.
Progress0 / 4 steps
1
Create the date string
Create a string variable called date and set it to "2024-06-15".
Ruby
Need a hint?

Use = to assign the string to the variable date.

2
Create the named capture regex
Create a regular expression variable called date_regex that matches the format YYYY-MM-DD using named captures for year, month, and day. Use the syntax /(?\d{4})-(?\d{2})-(?\d{2})/.
Ruby
Need a hint?

Use /.../ to create the regex and ? for named captures.

3
Match the date string with the regex
Use the match method to match date against date_regex and assign the result to a variable called match_data. Use match_data = date_regex.match(date).
Ruby
Need a hint?

Use the match method on the regex to get the match data.

4
Print the extracted year, month, and day
Print the year, month, and day from match_data using the named captures. Use puts match_data[:year], puts match_data[:month], and puts match_data[:day].
Ruby
Need a hint?

Use puts to print each part on its own line.