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