Bird
0
0

Which Ruby code correctly does this using gsub and a regex?

hard📝 Application Q15 of 15
Ruby - String Operations
Given the string "2023-04-01 and 2023-05-01", you want to replace only the month part (the two digits after the first dash) with '12' for all dates. Which Ruby code correctly does this using gsub and a regex?
A"2023-04-01 and 2023-05-01".sub(/-(\d{2})-/, '-12-')
B"2023-04-01 and 2023-05-01".gsub(/\d{2}-/, '12-')
C"2023-04-01 and 2023-05-01".gsub(/-(\d{2})-/, '-12-')
D"2023-04-01 and 2023-05-01".gsub(/-\d{2}/, '-12')
Step-by-Step Solution
Solution:
  1. Step 1: Identify the pattern to replace

    The month is the two digits between dashes, so the regex -(\d{2})- matches the dash, two digits, then dash.
  2. Step 2: Use gsub to replace all matches

    Using gsub with the pattern and replacement '-12-' replaces the month part in all dates.
  3. Final Answer:

    "2023-04-01 and 2023-05-01".gsub(/-(\d{2})-/, '-12-') -> Option C
  4. Quick Check:

    gsub with regex replaces all month parts correctly [OK]
Quick Trick: Use gsub with regex matching month pattern for all replacements [OK]
Common Mistakes:
  • Using sub instead of gsub for all matches
  • Incorrect regex missing dashes
  • Replacing wrong parts of the string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes