Bird
0
0

Given a string of dates like "2023-04-01, 2024-12-31", which Ruby code correctly extracts all year parts using capture groups?

hard📝 Application Q15 of 15
Ruby - Regular Expressions
Given a string of dates like "2023-04-01, 2024-12-31", which Ruby code correctly extracts all year parts using capture groups?
Adates.scan(/\d{4}-\d{2}-\d{2}/)
Bdates.match(/(\d{4})-\d{2}-\d{2}/)
Cdates.scan(/(\d{4})-\d{2}-\d{2}/).flatten
Ddates.match(/\d{4}/)
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal and methods

    We want all years from multiple dates. scan finds all matches, match finds only first.
  2. Step 2: Analyze each option

    dates.scan(/(\d{4})-\d{2}-\d{2}/).flatten uses scan with a capture group for year, returning all years as array. dates.match(/(\d{4})-\d{2}-\d{2}/) uses match which returns only first match. dates.scan(/\d{4}-\d{2}-\d{2}/) uses scan but no capture group, returns full dates. dates.match(/\d{4}/) uses match without capture group, only first year.
  3. Final Answer:

    dates.scan(/(\d{4})-\d{2}-\d{2}/).flatten -> Option C
  4. Quick Check:

    scan + capture group = all years [OK]
Quick Trick: Use scan with capture groups to get all matches [OK]
Common Mistakes:
  • Using match instead of scan for multiple matches
  • Not using capture groups to extract parts
  • Forgetting to flatten nested arrays from scan

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes