Bird
0
0

Given a string containing dates in format "YYYY-MM-DD", how would you replace all dashes with slashes only if the year starts with "202"?

hard📝 Application Q9 of 15
Ruby - Regular Expressions
Given a string containing dates in format "YYYY-MM-DD", how would you replace all dashes with slashes only if the year starts with "202"?
Astr.gsub(/202-/, '202/')
Bstr.gsub(/\d{4}-/, '202/')
Cstr.gsub(/(202\d)-/, '\1/')
Dstr.gsub(/202\d-\d{2}-\d{2}/, '2020/01/01')
Step-by-Step Solution
Solution:
  1. Step 1: Understand the regex with capture group

    The pattern /(202\d)-/ captures years starting with 202 and a digit, followed by a dash.
  2. Step 2: Replace dash with slash preserving year

    Using '\1/' replaces the dash with slash, keeping the year intact.
  3. Final Answer:

    str.gsub(/(202\d)-/, '\1/') -> Option C
  4. Quick Check:

    Use capture groups to keep parts and replace selectively [OK]
Quick Trick: Use parentheses to capture and reuse parts in replacement [OK]
Common Mistakes:
  • Replacing entire date instead of just dash
  • Not using capture groups to keep year
  • Replacing wrong parts of string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes